├── samples
├── android-java
│ ├── app
│ │ ├── .gitignore
│ │ ├── src
│ │ │ └── main
│ │ │ │ ├── res
│ │ │ │ ├── values
│ │ │ │ │ ├── dimens.xml
│ │ │ │ │ ├── strings.xml
│ │ │ │ │ ├── colors.xml
│ │ │ │ │ └── themes.xml
│ │ │ │ ├── mipmap-hdpi
│ │ │ │ │ ├── ic_launcher.webp
│ │ │ │ │ └── ic_launcher_round.webp
│ │ │ │ ├── mipmap-mdpi
│ │ │ │ │ ├── ic_launcher.webp
│ │ │ │ │ └── ic_launcher_round.webp
│ │ │ │ ├── mipmap-xhdpi
│ │ │ │ │ ├── ic_launcher.webp
│ │ │ │ │ └── ic_launcher_round.webp
│ │ │ │ ├── mipmap-xxhdpi
│ │ │ │ │ ├── ic_launcher.webp
│ │ │ │ │ └── ic_launcher_round.webp
│ │ │ │ ├── mipmap-xxxhdpi
│ │ │ │ │ ├── ic_launcher.webp
│ │ │ │ │ └── ic_launcher_round.webp
│ │ │ │ ├── mipmap-anydpi-v26
│ │ │ │ │ ├── ic_launcher.xml
│ │ │ │ │ └── ic_launcher_round.xml
│ │ │ │ ├── layout
│ │ │ │ │ └── activity_main.xml
│ │ │ │ └── drawable-v24
│ │ │ │ │ └── ic_launcher_foreground.xml
│ │ │ │ ├── assets
│ │ │ │ └── logback.xml
│ │ │ │ ├── AndroidManifest.xml
│ │ │ │ └── java
│ │ │ │ └── com
│ │ │ │ └── configcat
│ │ │ │ └── configcatsample
│ │ │ │ └── MainActivity.java
│ │ └── build.gradle
│ ├── settings.gradle
│ ├── .gitignore
│ ├── gradle
│ │ └── wrapper
│ │ │ └── gradle-wrapper.properties
│ ├── build.gradle
│ ├── gradle.properties
│ └── gradlew.bat
└── android-kotlin
│ ├── app
│ ├── .gitignore
│ ├── src
│ │ ├── main
│ │ │ ├── res
│ │ │ │ ├── values
│ │ │ │ │ ├── strings.xml
│ │ │ │ │ ├── colors.xml
│ │ │ │ │ └── styles.xml
│ │ │ │ ├── mipmap-hdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-mdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xhdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xxhdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-xxxhdpi
│ │ │ │ │ ├── ic_launcher.png
│ │ │ │ │ └── ic_launcher_round.png
│ │ │ │ ├── mipmap-anydpi-v26
│ │ │ │ │ ├── ic_launcher.xml
│ │ │ │ │ └── ic_launcher_round.xml
│ │ │ │ ├── layout
│ │ │ │ │ └── activity_main.xml
│ │ │ │ └── drawable-v24
│ │ │ │ │ └── ic_launcher_foreground.xml
│ │ │ ├── AndroidManifest.xml
│ │ │ └── java
│ │ │ │ └── com
│ │ │ │ └── configcat
│ │ │ │ └── configcatsample
│ │ │ │ └── MainActivity.kt
│ │ └── android-logger.properties
│ ├── proguard-rules.pro
│ └── build.gradle
│ ├── settings.gradle
│ ├── .gitignore
│ ├── gradle
│ └── wrapper
│ │ └── gradle-wrapper.properties
│ ├── gradle.properties
│ ├── build.gradle
│ └── gradlew.bat
├── .github
├── CODEOWNERS
├── dependabot.yml
└── workflows
│ ├── stale.yml
│ ├── scheduled-test.yml
│ ├── test.yml
│ └── android-ci.yml
├── gradle.properties
├── settings.gradle
├── src
├── test
│ ├── resources
│ │ ├── specialCharacters.txt
│ │ ├── evaluation
│ │ │ ├── simple_value
│ │ │ │ ├── on_flag.txt
│ │ │ │ ├── int_setting.txt
│ │ │ │ ├── off_flag.txt
│ │ │ │ ├── text_setting.txt
│ │ │ │ └── double_setting.txt
│ │ │ ├── 1_targeting_rule
│ │ │ │ ├── 1_rule_not_matching_targeted_attribute.txt
│ │ │ │ ├── 1_rule_matching_targeted_attribute.txt
│ │ │ │ ├── 1_rule_no_user.txt
│ │ │ │ └── 1_rule_no_targeted_attribute.txt
│ │ │ ├── options_after_targeting_rule
│ │ │ │ ├── options_after_targeting_rule_matching_targeted_attribute.txt
│ │ │ │ ├── options_after_targeting_rule_not_matching_targeted_attribute.txt
│ │ │ │ ├── options_after_targeting_rule_no_user.txt
│ │ │ │ └── options_after_targeting_rule_no_targeted_attribute.txt
│ │ │ ├── number_validation.json
│ │ │ ├── list_truncation.json
│ │ │ ├── options_within_targeting_rule
│ │ │ │ ├── options_within_targeting_rule_not_matching_targeted_attribute.txt
│ │ │ │ ├── options_within_targeting_rule_matching_targeted_attribute_options_attribute.txt
│ │ │ │ ├── options_within_targeting_rule_no_user.txt
│ │ │ │ ├── options_within_targeting_rule_no_targeted_attribute.txt
│ │ │ │ └── options_within_targeting_rule_matching_targeted_attribute_no_options_attribute.txt
│ │ │ ├── options_based_on_user_id
│ │ │ │ ├── options_user_attribute_user.txt
│ │ │ │ └── options_user_attribute_no_user.txt
│ │ │ ├── epoch_date_validation.json
│ │ │ ├── options_based_on_custom_attr
│ │ │ │ ├── matching_options_custom_attribute.txt
│ │ │ │ ├── no_options_custom_attribute.txt
│ │ │ │ └── options_custom_attribute_no_user.txt
│ │ │ ├── and_rules
│ │ │ │ ├── and_rules_user.txt
│ │ │ │ └── and_rules_no_user.txt
│ │ │ ├── comparators.json
│ │ │ ├── and_rules.json
│ │ │ ├── list_truncation
│ │ │ │ ├── list_truncation.txt
│ │ │ │ └── test_list_truncation.json
│ │ │ ├── segment
│ │ │ │ ├── segment_matching.txt
│ │ │ │ ├── segment_no_matching.txt
│ │ │ │ ├── segment_no_user.txt
│ │ │ │ ├── segment_no_user_multi_conditions.txt
│ │ │ │ └── segment_no_targeted_attribute.txt
│ │ │ ├── options_based_on_user_id.json
│ │ │ ├── semver_validation.json
│ │ │ ├── number_validation
│ │ │ │ └── number_error.txt
│ │ │ ├── 2_targeting_rules
│ │ │ │ ├── 2_rules_not_matching_targeted_attribute.txt
│ │ │ │ ├── 2_rules_matching_targeted_attribute.txt
│ │ │ │ ├── 2_rules_no_user.txt
│ │ │ │ └── 2_rules_no_targeted_attribute.txt
│ │ │ ├── epoch_date_validation
│ │ │ │ └── date_error.txt
│ │ │ ├── options_based_on_custom_attr.json
│ │ │ ├── simple_value.json
│ │ │ ├── 2_targeting_rules.json
│ │ │ ├── 1_targeting_rule.json
│ │ │ ├── prerequisite_flag
│ │ │ │ ├── prerequisite_flag_no_user_needed_by_dep.txt
│ │ │ │ ├── prerequisite_flag_multilevel.txt
│ │ │ │ ├── prerequisite_flag_no_user_needed_by_prereq.txt
│ │ │ │ ├── prerequisite_flag.txt
│ │ │ │ └── prerequisite_flag_no_user_needed_by_both.txt
│ │ │ ├── prerequisite_flag.json
│ │ │ ├── options_after_targeting_rule.json
│ │ │ ├── segment.json
│ │ │ ├── semver_validation
│ │ │ │ ├── semver_error.txt
│ │ │ │ └── semver_relations_error.txt
│ │ │ ├── options_within_targeting_rule.json
│ │ │ └── comparators
│ │ │ │ └── allinone.txt
│ │ ├── matrix
│ │ │ ├── testmatrix_sensitive.csv
│ │ │ ├── testmatrix_segment.csv
│ │ │ ├── testmatrix_variationId.csv
│ │ │ ├── testmatrix_number.csv
│ │ │ ├── testmatrix_segments_old.csv
│ │ │ ├── testmatrix_prerequisite_flag.csv
│ │ │ ├── testmatrix_and_or.csv
│ │ │ ├── testmatrix_unicode.csv
│ │ │ ├── testmatrix_semantic_2.csv
│ │ │ └── testmatrix_semantic.csv
│ │ └── test_circulardependency.json
│ ├── .DS_Store
│ └── java
│ │ └── com
│ │ └── configcat
│ │ ├── ClassPathResourceOverrideDataSource.java
│ │ ├── TestCache.java
│ │ ├── UserTests.java
│ │ ├── FormattableLogMessageTests.java
│ │ ├── Helpers.java
│ │ ├── EvaluationLoggerTurnOffTest.java
│ │ └── EntrySerializationTest.java
├── .DS_Store
└── main
│ ├── java
│ └── com
│ │ └── configcat
│ │ ├── PollingMode.java
│ │ ├── ConditionAccessor.java
│ │ ├── NullConfigCache.java
│ │ ├── DataGovernance.java
│ │ ├── LogLevel.java
│ │ ├── Preferences.java
│ │ ├── SettingType.java
│ │ ├── RefreshResult.java
│ │ ├── Segment.java
│ │ ├── ClientCacheState.java
│ │ ├── FormattableLogMessageWithUserCondition.java
│ │ ├── SegmentCondition.java
│ │ ├── OverrideDataSource.java
│ │ ├── Condition.java
│ │ ├── LogFilterFunction.java
│ │ ├── SharedPreferencesCache.java
│ │ ├── ConfigCache.java
│ │ ├── DateTimeUtils.java
│ │ ├── PercentageOption.java
│ │ ├── SegmentComparator.java
│ │ ├── PrerequisiteComparator.java
│ │ ├── FormattableLogMessage.java
│ │ ├── FormattableLogMessageWithKeySet.java
│ │ ├── OverrideBehaviour.java
│ │ ├── PrerequisiteFlagCondition.java
│ │ ├── Config.java
│ │ ├── EvaluationContext.java
│ │ ├── TargetingRule.java
│ │ ├── LocalMapDataSource.java
│ │ ├── UserCondition.java
│ │ ├── Setting.java
│ │ ├── SettingValue.java
│ │ ├── Entry.java
│ │ ├── ConfigCatLogger.java
│ │ ├── Utils.java
│ │ ├── UserAttributeConverter.java
│ │ ├── EvaluationDetails.java
│ │ └── PollingModes.java
│ └── AndroidManifest.xml
├── .DS_Store
├── .vscode
└── settings.json
├── media
└── readme02-3.png
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
└── libs.versions.toml
├── CHANGELOG.md
├── .gitignore
├── configcat-proguard-rules.pro
├── LICENSE
├── DEPLOY.md
├── CONTRIBUTING.md
└── gradlew.bat
/samples/android-java/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | * @configcat/developers
2 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/samples/android-kotlin/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | version=10.4.3
2 |
3 | org.gradle.jvmargs=-Xmx2g
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'configcat-android-client'
2 |
--------------------------------------------------------------------------------
/src/test/resources/specialCharacters.txt:
--------------------------------------------------------------------------------
1 | äöüÄÖÜçéèñışğ⢙✓😀
2 |
--------------------------------------------------------------------------------
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/.DS_Store
--------------------------------------------------------------------------------
/src/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/src/.DS_Store
--------------------------------------------------------------------------------
/src/test/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/src/test/.DS_Store
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "java.configuration.updateBuildConfiguration": "automatic"
3 | }
--------------------------------------------------------------------------------
/media/readme02-3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/media/readme02-3.png
--------------------------------------------------------------------------------
/samples/android-java/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = "ConfigCat Android Java Sample"
2 | include ':app'
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/src/test/resources/evaluation/simple_value/on_flag.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'boolDefaultTrue'
2 | Returning 'true'.
3 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/simple_value/int_setting.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'integerDefaultOne'
2 | Returning '1'.
3 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/simple_value/off_flag.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'boolDefaultFalse'
2 | Returning 'false'.
3 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/simple_value/text_setting.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'stringDefaultCat'
2 | Returning 'Cat'.
3 |
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 | 16dp
3 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/simple_value/double_setting.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'doubleDefaultPi'
2 | Returning '3.1415'.
3 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ConfigCatSample
3 |
4 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | Please check the [Github Releases](https://github.com/configcat/android-sdk/releases) page for the changelog of the ConfigCat Android SDK.
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-hdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-java/app/src/main/res/mipmap-hdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-mdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-java/app/src/main/res/mipmap-mdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-xhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-java/app/src/main/res/mipmap-xhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-java/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | enable-beta-ecosystems: true
3 | updates:
4 | - package-ecosystem: "github-actions"
5 | directory: "/"
6 | schedule:
7 | interval: "weekly"
8 |
--------------------------------------------------------------------------------
/samples/android-java/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-java/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp
--------------------------------------------------------------------------------
/samples/android-kotlin/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 | .externalNativeBuild
10 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-kotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-kotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-java/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-java/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-java/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-kotlin/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-kotlin/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-java/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-java/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-kotlin/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-kotlin/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/configcat/android-sdk/HEAD/samples/android-kotlin/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ConfigCat Android Java Sample
3 | MainActivity
4 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/PollingMode.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * The base class of a polling mode configuration.
5 | */
6 | public interface PollingMode {
7 | String getPollingIdentifier();
8 | }
9 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/android-logger.properties:
--------------------------------------------------------------------------------
1 | root=ERROR:MyApplication
2 | # DEBUG (and higher) messages from classes of com.example.database
3 | # will be logged with "MyApplication-Database" tag
4 | logger.com.configcat=DEBUG
--------------------------------------------------------------------------------
/.github/workflows/stale.yml:
--------------------------------------------------------------------------------
1 | name: Mark stale issues
2 |
3 | on:
4 | schedule:
5 | - cron: '0 1 * * *'
6 |
7 | workflow_dispatch:
8 |
9 | jobs:
10 | stale:
11 | uses: configcat/.github/.github/workflows/stale.yml@master
12 | secrets: inherit
13 |
--------------------------------------------------------------------------------
/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Aug 04 20:00:01 CEST 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/ConditionAccessor.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | interface ConditionAccessor {
4 | UserCondition getUserCondition();
5 |
6 | SegmentCondition getSegmentCondition();
7 |
8 | PrerequisiteFlagCondition getPrerequisiteFlagCondition();
9 | }
10 |
--------------------------------------------------------------------------------
/samples/android-java/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Jan 05 11:38:37 CET 2023
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/samples/android-kotlin/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Sep 22 18:23:09 CEST 2022
2 | distributionBase=GRADLE_USER_HOME
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-bin.zip
4 | distributionPath=wrapper/dists
5 | zipStorePath=wrapper/dists
6 | zipStoreBase=GRADLE_USER_HOME
7 |
--------------------------------------------------------------------------------
/src/test/resources/matrix/testmatrix_sensitive.csv:
--------------------------------------------------------------------------------
1 | Identifier;Email;Country;Custom1;isOneOfSensitive;isNotOneOfSensitive
2 | ##null##;;;;ToAll;ToAll
3 | id1;macska@example.com;;;Macska;Kigyo
4 | Kutya;;;;Allat;ToAll
5 | Sas;;;;ToAll;Kigyo
6 | Kutya;macska@example.com;;;Macska;ToAll
7 | id1;;Scotland;;Britt;Kigyo
8 | Macska;;USA;;ToAll;Ireland
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/1_targeting_rule/1_rule_not_matching_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'stringContainsDogDefaultCat' for User '{"Identifier":"12345","Email":"joe@example.com"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN 'Dog' => no match
4 | Returning 'Cat'.
5 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/1_targeting_rule/1_rule_matching_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'stringContainsDogDefaultCat' for User '{"Identifier":"12345","Email":"joe@configcat.com"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN 'Dog' => MATCH, applying rule
4 | Returning 'Dog'.
5 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/NullConfigCache.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * A null cache implementation.
5 | */
6 | class NullConfigCache extends ConfigCache {
7 |
8 | @Override
9 | protected String read(String key) {
10 | return null;
11 | }
12 |
13 | @Override
14 | protected void write(String key, String value) { /* do nothing */ }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_after_targeting_rule/options_after_targeting_rule_matching_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'integer25One25Two25Three25FourAdvancedRules' for User '{"Identifier":"12345","Email":"joe@configcat.com"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN '5' => MATCH, applying rule
4 | Returning '5'.
5 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/number_validation.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "PKDVCLf-Hq-h-kCzMp-L7Q/uGyK3q9_ckmdxRyI7vjwCw",
3 | "tests": [
4 | {
5 | "key": "number",
6 | "defaultValue": "default",
7 | "returnValue": "Default",
8 | "expectedLog": "number_error.txt",
9 | "user": {
10 | "Identifier": "12345",
11 | "Custom1": "not_a_number"
12 | }
13 | }
14 | ]
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/list_truncation.json:
--------------------------------------------------------------------------------
1 | {
2 | "jsonOverride": "test_list_truncation.json",
3 | "sdkKey": "configcat-sdk-test-key/0000000000000000000001",
4 | "tests": [
5 | {
6 | "key": "booleanKey1",
7 | "defaultValue": false,
8 | "user": {
9 | "Identifier": "12"
10 | },
11 | "returnValue": true,
12 | "expectedLog": "list_truncation.txt"
13 | }
14 | ]
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_within_targeting_rule/options_within_targeting_rule_not_matching_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'stringContainsString75Cat0Dog25Falcon0HorseDefaultCat' for User '{"Identifier":"12345","Email":"joe@example.com"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN % options => no match
4 | Returning 'Cat'.
5 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_based_on_user_id/options_user_attribute_user.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'string75Cat0Dog25Falcon0Horse' for User '{"Identifier":"12345"}'
2 | Evaluating % options based on the User.Identifier attribute:
3 | - Computing hash in the [0..99] range from User.Identifier => 21 (this value is sticky and consistent across all SDKs)
4 | - Hash value 21 selects % option 1 (75%), 'Cat'.
5 | Returning 'Cat'.
6 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/epoch_date_validation.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "configcat-sdk-1/JcPbCGl_1E-K9M-fJOyKyQ/OfQqcTjfFUGBwMKqtyEOrQ",
3 | "tests": [
4 | {
5 | "key": "boolTrueIn202304",
6 | "defaultValue": true,
7 | "returnValue": false,
8 | "expectedLog": "date_error.txt",
9 | "user": {
10 | "Identifier": "12345",
11 | "Custom1": "2023.04.10"
12 | }
13 | }
14 | ]
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_based_on_custom_attr/matching_options_custom_attribute.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'string75Cat0Dog25Falcon0HorseCustomAttr' for User '{"Identifier":"12345","Country":"US"}'
2 | Evaluating % options based on the User.Country attribute:
3 | - Computing hash in the [0..99] range from User.Country => 70 (this value is sticky and consistent across all SDKs)
4 | - Hash value 70 selects % option 1 (75%), 'Cat'.
5 | Returning 'Cat'.
6 |
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/DataGovernance.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * Describes the location of your feature flag and setting data within the ConfigCat CDN.
5 | */
6 | public enum DataGovernance {
7 | /**
8 | * Select this if your feature flags are published to all global CDN nodes.
9 | */
10 | GLOBAL,
11 | /**
12 | * Select this if your feature flags are published to CDN nodes only in the EU.
13 | */
14 | EU_ONLY
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/LogLevel.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * Describes the log level.
5 | */
6 | public enum LogLevel {
7 | /**
8 | * Debug level.
9 | */
10 | DEBUG,
11 | /**
12 | * Info level.
13 | */
14 | INFO,
15 | /**
16 | * Warning level.
17 | */
18 | WARNING,
19 | /**
20 | * Error level.
21 | */
22 | ERROR,
23 | /**
24 | * Turns logging off.
25 | */
26 | NO_LOG,
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/and_rules/and_rules_user.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'emailAnd' for User '{"Identifier":"12345","Email":"jane@configcat.com"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF User.Email STARTS WITH ANY OF [<1 hashed value>] => true
4 | AND User.Email CONTAINS ANY OF ['@'] => true
5 | AND User.Email ENDS WITH ANY OF [<1 hashed value>] => false, skipping the remaining AND conditions
6 | THEN 'Dog' => no match
7 | Returning 'Cat'.
8 |
--------------------------------------------------------------------------------
/src/test/resources/matrix/testmatrix_segment.csv:
--------------------------------------------------------------------------------
1 | Identifier;Email;Country;Custom1;developerAndBetaUserSegment;developerAndBetaUserCleartextSegment;notDeveloperAndNotBetaUserSegment;notDeveloperAndNotBetaUserCleartextSegment
2 | ##null##;;;;False;False;False;False
3 | ;;;;False;False;False;False
4 | john@example.com;john@example.com;##null##;##null##;False;False;False;False
5 | jane@example.com;jane@example.com;##null##;##null##;False;False;False;False
6 | kate@example.com;kate@example.com;##null##;##null##;True;True;True;True
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .classpath
2 | .project
3 | .settings
4 | bin
5 | # Compiled class file
6 | *.class
7 |
8 | # Log file
9 | *.log
10 |
11 | # BlueJ files
12 | *.ctxt
13 |
14 | # Mobile Tools for Java (J2ME)
15 | .mtj.tmp/
16 |
17 | # Package Files #
18 | *.jar
19 | *.war
20 | *.ear
21 | *.zip
22 | *.tar.gz
23 | *.rar
24 |
25 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
26 | hs_err_pid*
27 |
28 | **/.idea/*
29 |
30 | **/.gradle/*
31 | **/build/*
32 | out/
33 |
34 | .DS_Store
35 | local.properties
36 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_based_on_user_id/options_user_attribute_no_user.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'string75Cat0Dog25Falcon0Horse' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'string75Cat0Dog25Falcon0Horse'
3 | Skipping % options because the User Object is missing.
4 | Returning 'Chicken'.
5 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/comparators.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "configcat-sdk-1/JcPbCGl_1E-K9M-fJOyKyQ/OfQqcTjfFUGBwMKqtyEOrQ",
3 | "tests": [
4 | {
5 | "key": "allinone",
6 | "defaultValue": "",
7 | "user": {
8 | "Identifier": "12345",
9 | "Email": "joe@example.com",
10 | "Country": "[\"USA\"]",
11 | "Version": "1.0.0",
12 | "Number": "1.0",
13 | "Date": "1693497500"
14 | },
15 | "returnValue": "default",
16 | "expectedLog": "allinone.txt"
17 | }
18 | ]
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_based_on_custom_attr/no_options_custom_attribute.txt:
--------------------------------------------------------------------------------
1 | WARNING [3003] Cannot evaluate % options for setting 'string75Cat0Dog25Falcon0HorseCustomAttr' (the User.Country attribute is missing). You should set the User.Country attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'string75Cat0Dog25Falcon0HorseCustomAttr' for User '{"Identifier":"12345"}'
3 | Skipping % options because the User.Country attribute is missing.
4 | Returning 'Chicken'.
5 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_based_on_custom_attr/options_custom_attribute_no_user.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'string75Cat0Dog25Falcon0HorseCustomAttr' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'string75Cat0Dog25Falcon0HorseCustomAttr'
3 | Skipping % options because the User Object is missing.
4 | Returning 'Chicken'.
5 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/Preferences.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | class Preferences {
6 | @SerializedName(value = "u")
7 | private String baseUrl;
8 | @SerializedName(value = "r")
9 | private int redirect;
10 | @SerializedName(value = "s")
11 | private String salt;
12 |
13 | public String getBaseUrl() {
14 | return baseUrl;
15 | }
16 |
17 | public int getRedirect() {
18 | return redirect;
19 | }
20 |
21 | public String getSalt() {
22 | return salt;
23 | }
24 | }
--------------------------------------------------------------------------------
/src/test/resources/evaluation/and_rules.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "configcat-sdk-1/JcPbCGl_1E-K9M-fJOyKyQ/ByMO9yZNn02kXcm72lnY1A",
3 | "tests": [
4 | {
5 | "key": "emailAnd",
6 | "defaultValue": "default",
7 | "returnValue": "Cat",
8 | "expectedLog": "and_rules_no_user.txt"
9 | },
10 | {
11 | "key": "emailAnd",
12 | "defaultValue": "default",
13 | "user": {
14 | "Identifier": "12345",
15 | "Email": "jane@configcat.com"
16 | },
17 | "returnValue": "Cat",
18 | "expectedLog": "and_rules_user.txt"
19 | }
20 | ]
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/list_truncation/list_truncation.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'booleanKey1' for User '{"Identifier":"12"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF User.Identifier CONTAINS ANY OF ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] => true
4 | AND User.Identifier CONTAINS ANY OF ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', ... <1 more value>] => true
5 | AND User.Identifier CONTAINS ANY OF ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', ... <2 more values>] => true
6 | THEN 'true' => MATCH, applying rule
7 | Returning 'true'.
8 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/segment/segment_matching.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'featureWithSegmentTargeting' for User '{"Identifier":"12345","Email":"jane@example.com"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF User IS IN SEGMENT 'Beta users'
4 | (
5 | Evaluating segment 'Beta users':
6 | - IF User.Email IS ONE OF [<2 hashed values>] => true
7 | Segment evaluation result: User IS IN SEGMENT.
8 | Condition (User IS IN SEGMENT 'Beta users') evaluates to true.
9 | )
10 | THEN 'true' => MATCH, applying rule
11 | Returning 'true'.
12 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/segment/segment_no_matching.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'featureWithNegatedSegmentTargeting' for User '{"Identifier":"12345","Email":"jane@example.com"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF User IS NOT IN SEGMENT 'Beta users'
4 | (
5 | Evaluating segment 'Beta users':
6 | - IF User.Email IS ONE OF [<2 hashed values>] => true
7 | Segment evaluation result: User IS IN SEGMENT.
8 | Condition (User IS NOT IN SEGMENT 'Beta users') evaluates to false.
9 | )
10 | THEN 'true' => no match
11 | Returning 'false'.
12 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_based_on_user_id.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "PKDVCLf-Hq-h-kCzMp-L7Q/psuH7BGHoUmdONrzzUOY7A",
3 | "tests": [
4 | {
5 | "key": "string75Cat0Dog25Falcon0Horse",
6 | "defaultValue": "default",
7 | "returnValue": "Chicken",
8 | "expectedLog": "options_user_attribute_no_user.txt"
9 | },
10 | {
11 | "key": "string75Cat0Dog25Falcon0Horse",
12 | "defaultValue": "default",
13 | "user": {
14 | "Identifier": "12345"
15 | },
16 | "returnValue": "Cat",
17 | "expectedLog": "options_user_attribute_user.txt"
18 | }
19 | ]
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/SettingType.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | /**
6 | * Setting type.
7 | */
8 | public enum SettingType {
9 | /**
10 | * On/off type (feature flag).
11 | */
12 | @SerializedName("0")
13 | BOOLEAN,
14 |
15 | /**
16 | * Text type.
17 | */
18 | @SerializedName("1")
19 | STRING,
20 |
21 | /**
22 | * Whole number type.
23 | */
24 | @SerializedName("2")
25 | INT,
26 |
27 | /**
28 | * Decimal number type.
29 | */
30 | @SerializedName("3")
31 | DOUBLE,
32 | }
33 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/RefreshResult.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * Represents the result of a forceRefresh() call.
5 | */
6 | public class RefreshResult {
7 | private final boolean success;
8 | private final Object error;
9 |
10 | RefreshResult(boolean success, Object error) {
11 | this.success = success;
12 | this.error = error;
13 | }
14 |
15 | public boolean isSuccess() {
16 | return success;
17 | }
18 |
19 | public String error() {
20 | if(error != null) {
21 | return error.toString();
22 | }
23 | return null;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_after_targeting_rule/options_after_targeting_rule_not_matching_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'integer25One25Two25Three25FourAdvancedRules' for User '{"Identifier":"12345","Email":"joe@example.com"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN '5' => no match
4 | Evaluating % options based on the User.Identifier attribute:
5 | - Computing hash in the [0..99] range from User.Identifier => 25 (this value is sticky and consistent across all SDKs)
6 | - Hash value 25 selects % option 2 (25%), '2'.
7 | Returning '2'.
8 |
--------------------------------------------------------------------------------
/src/test/resources/matrix/testmatrix_variationId.csv:
--------------------------------------------------------------------------------
1 | Identifier;Email;Country;Custom1;boolean;decimal;text;whole
2 | ##null##;;;;a0e56eda;63612d39;3f05be89;cf2e9162;
3 | a@configcat.com;a@configcat.com;Hungary;admin;67787ae4;8f9559cf;9bdc6a1f;ab30533b;
4 | b@configcat.com;b@configcat.com;Hungary;admin;67787ae4;8f9559cf;9bdc6a1f;ab30533b;
5 | a@test.com;a@test.com;Hungary;admin;67787ae4;d66c5781;65310deb;ec14f6a9;
6 | b@test.com;b@test.com;Hungary;admin;a0e56eda;d66c5781;65310deb;ec14f6a9;
7 | cliffordj@aol.com;cliffordj@aol.com;Hungary;admin;67787ae4;8155ad7b;cf19e913;ec14f6a9;
8 | bryanw@verizon.net;bryanw@verizon.net;Hungary;;a0e56eda;d0dbc27f;30ba32b9;61a5a033;
9 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/segment/segment_no_user.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'featureWithSegmentTargeting' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'featureWithSegmentTargeting'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User IS IN SEGMENT 'Beta users' THEN 'true' => cannot evaluate, User Object is missing
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | Returning 'false'.
7 |
--------------------------------------------------------------------------------
/src/test/resources/matrix/testmatrix_number.csv:
--------------------------------------------------------------------------------
1 | Identifier;Email;Country;Custom1;numberWithPercentage;number
2 | ##null##;;;;Default;Default
3 | id1;;;0;<2.1;<>5
4 | id1;;;0.0;<2.1;<>5
5 | id1;;;0,0;<2.1;<>5
6 | id1;;;0.2;<2.1;<>5
7 | id2;;;0,2;<2.1;<>5
8 | id3;;;1;<2.1;<>5
9 | id4;;;1.0;<2.1;<>5
10 | id5;;;1,0;<2.1;<>5
11 | id6;;;1.5;<2.1;<>5
12 | id7;;;1,5;<2.1;<>5
13 | id8;;;2.1;<=2,1;<>5
14 | id9;;;2,1;<=2,1;<>5
15 | id10;;;3.50;=3.5;<>5
16 | id11;;;3,50;=3.5;<>5
17 | id12;;;5;>=5;Default
18 | id13;;;5.0;>=5;Default
19 | id14;;;5,0;>=5;Default
20 | id13;;;5.76;>5;<>5
21 | id14;;;5,76;>5;<>5
22 | id15;;;4;<>4.2;<>5
23 | id16;;;4.0;<>4.2;<>5
24 | id17;;;4,0;<>4.2;<>5
25 | id18;;;4.2;80%;<>5
26 | id19;;;4,2;20%;<>5
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_within_targeting_rule/options_within_targeting_rule_matching_targeted_attribute_options_attribute.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'stringContainsString75Cat0Dog25Falcon0HorseDefaultCat' for User '{"Identifier":"12345","Email":"joe@configcat.com","Country":"US"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN % options => MATCH, applying rule
4 | Evaluating % options based on the User.Country attribute:
5 | - Computing hash in the [0..99] range from User.Country => 63 (this value is sticky and consistent across all SDKs)
6 | - Hash value 63 selects % option 1 (75%), 'Cat'.
7 | Returning 'Cat'.
8 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/semver_validation.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "PKDVCLf-Hq-h-kCzMp-L7Q/BAr3KgLTP0ObzKnBTo5nhA",
3 | "tests": [
4 | {
5 | "key": "isNotOneOf",
6 | "defaultValue": "default",
7 | "returnValue": "Default",
8 | "expectedLog": "semver_error.txt",
9 | "user": {
10 | "Identifier": "12345",
11 | "Custom1": "wrong_semver"
12 | }
13 | },
14 | {
15 | "key": "relations",
16 | "defaultValue": "default",
17 | "returnValue": "Default",
18 | "expectedLog": "semver_relations_error.txt",
19 | "user": {
20 | "Identifier": "12345",
21 | "Custom1": "wrong_semver"
22 | }
23 | }
24 | ]
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/number_validation/number_error.txt:
--------------------------------------------------------------------------------
1 | WARNING [3004] Cannot evaluate condition (User.Custom1 != '5') for setting 'number' ('not_a_number' is not a valid decimal number). Please check the User.Custom1 attribute and make sure that its value corresponds to the comparison operator.
2 | INFO [5000] Evaluating 'number' for User '{"Identifier":"12345","Custom1":"not_a_number"}'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Custom1 != '5' THEN '<>5' => cannot evaluate, the User.Custom1 attribute is invalid ('not_a_number' is not a valid decimal number)
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | Returning 'Default'.
7 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/Segment.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | /**
6 | * ConfigCat segment.
7 | */
8 | public class Segment {
9 |
10 | @SerializedName(value = "n")
11 | private String name;
12 | @SerializedName(value = "r")
13 | private UserCondition[] segmentRules;
14 |
15 | /**
16 | * The name of the segment.
17 | */
18 | public String getName() {
19 | return name;
20 | }
21 |
22 | /**
23 | * The list of segment rule conditions (where there is a logical AND relation between the items).
24 | */
25 | public UserCondition[] getSegmentRules() {
26 | return segmentRules;
27 | }
28 | }
--------------------------------------------------------------------------------
/src/test/resources/evaluation/1_targeting_rule/1_rule_no_user.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'stringContainsDogDefaultCat' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'stringContainsDogDefaultCat'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN 'Dog' => cannot evaluate, User Object is missing
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | Returning 'Cat'.
7 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/ClientCacheState.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * Describes the Client state.
5 | */
6 | public enum ClientCacheState {
7 | /**
8 | * The SDK has no feature flag data neither from the cache nor from the ConfigCat CDN.
9 | */
10 | NO_FLAG_DATA,
11 | /**
12 | * The SDK runs with local only feature flag data.
13 | */
14 | HAS_LOCAL_OVERRIDE_FLAG_DATA_ONLY,
15 | /**
16 | * The SDK has feature flag data to work with only from the cache.
17 | */
18 | HAS_CACHED_FLAG_DATA_ONLY,
19 | /**
20 | * The SDK works with the latest feature flag data received from the ConfigCat CDN.
21 | */
22 | HAS_UP_TO_DATE_FLAG_DATA,
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/FormattableLogMessageWithUserCondition.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | class FormattableLogMessageWithUserCondition extends FormattableLogMessage {
4 |
5 | FormattableLogMessageWithUserCondition(String message, Object... args) {
6 | super(message,args);
7 | }
8 |
9 | @Override
10 | protected String formatLogMessage() {
11 | Object userConditionObject = args[0];
12 | if(userConditionObject instanceof UserCondition) {
13 | UserCondition userCondition = (UserCondition) userConditionObject;
14 | args[0] = EvaluateLogger.formatUserCondition(userCondition);
15 | }
16 | return String.format(message, args);
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/com/configcat/ClassPathResourceOverrideDataSource.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import java.io.IOException;
4 | import java.util.Map;
5 |
6 | public class ClassPathResourceOverrideDataSource extends OverrideDataSource {
7 | private final Map loadedSettings;
8 |
9 | @Override
10 | public Map getLocalConfiguration() {
11 | return this.loadedSettings;
12 | }
13 |
14 | public ClassPathResourceOverrideDataSource(String fileName) throws IOException {
15 | String contents = Helpers.readFileFromClassPath(fileName);
16 | Config config = Utils.deserializeConfig(contents);
17 | this.loadedSettings = config.getEntries();
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/and_rules/and_rules_no_user.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'emailAnd' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'emailAnd'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email STARTS WITH ANY OF [<1 hashed value>] => false, skipping the remaining AND conditions
5 | THEN 'Dog' => cannot evaluate, User Object is missing
6 | The current targeting rule is ignored and the evaluation continues with the next rule.
7 | Returning 'Cat'.
8 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/1_targeting_rule/1_rule_no_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | WARNING [3003] Cannot evaluate condition (User.Email CONTAINS ANY OF ['@configcat.com']) for setting 'stringContainsDogDefaultCat' (the User.Email attribute is missing). You should set the User.Email attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'stringContainsDogDefaultCat' for User '{"Identifier":"12345"}'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN 'Dog' => cannot evaluate, the User.Email attribute is missing
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | Returning 'Cat'.
7 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/SegmentCondition.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | /**
6 | * Describes a condition that is based on a segment.
7 | */
8 | public class SegmentCondition {
9 |
10 | @SerializedName(value = "s")
11 | private int segmentIndex;
12 | @SerializedName(value = "c")
13 | private int segmentComparator;
14 |
15 | /**
16 | * The index of the segment that the condition is based on.
17 | */
18 | public int getSegmentIndex() {
19 | return segmentIndex;
20 | }
21 |
22 | /**
23 | * The operator which defines the expected result of the evaluation of the segment.
24 | */
25 | public int getSegmentComparator() {
26 | return segmentComparator;
27 | }
28 | }
--------------------------------------------------------------------------------
/src/test/resources/matrix/testmatrix_segments_old.csv:
--------------------------------------------------------------------------------
1 | Identifier;Email;Country;Custom1;featureWithSegmentTargeting;featureWithSegmentTargetingCleartext;featureWithNegatedSegmentTargeting;featureWithNegatedSegmentTargetingCleartext;featureWithSegmentTargetingInverse;featureWithSegmentTargetingInverseCleartext;featureWithNegatedSegmentTargetingInverse;featureWithNegatedSegmentTargetingInverseCleartext
2 | ##null##;;;;False;False;False;False;False;False;False;False
3 | ;;;;False;False;False;False;False;False;False;False
4 | john@example.com;john@example.com;##null##;##null##;True;True;False;False;False;False;True;True
5 | jane@example.com;jane@example.com;##null##;##null##;True;True;False;False;False;False;True;True
6 | kate@example.com;kate@example.com;##null##;##null##;False;False;True;True;True;True;False;False
7 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_within_targeting_rule/options_within_targeting_rule_no_user.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'stringContainsString75Cat0Dog25Falcon0HorseDefaultCat' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'stringContainsString75Cat0Dog25Falcon0HorseDefaultCat'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN % options => cannot evaluate, User Object is missing
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | Returning 'Cat'.
7 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/segment/segment_no_user_multi_conditions.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'featureWithSegmentTargetingMultipleConditions' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'featureWithSegmentTargetingMultipleConditions'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User IS IN SEGMENT 'Beta users (cleartext)' => false, skipping the remaining AND conditions
5 | THEN 'true' => cannot evaluate, User Object is missing
6 | The current targeting rule is ignored and the evaluation continues with the next rule.
7 | Returning 'false'.
8 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_after_targeting_rule/options_after_targeting_rule_no_user.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'integer25One25Two25Three25FourAdvancedRules' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'integer25One25Two25Three25FourAdvancedRules'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN '5' => cannot evaluate, User Object is missing
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | Skipping % options because the User Object is missing.
7 | Returning '-1'.
8 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_within_targeting_rule/options_within_targeting_rule_no_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | WARNING [3003] Cannot evaluate condition (User.Email CONTAINS ANY OF ['@configcat.com']) for setting 'stringContainsString75Cat0Dog25Falcon0HorseDefaultCat' (the User.Email attribute is missing). You should set the User.Email attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'stringContainsString75Cat0Dog25Falcon0HorseDefaultCat' for User '{"Identifier":"12345"}'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN % options => cannot evaluate, the User.Email attribute is missing
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | Returning 'Cat'.
7 |
--------------------------------------------------------------------------------
/configcat-proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # ConfigCat Android SDK Proguard rules
2 |
3 | -keep class com.configcat.Config { *; }
4 | -keep class com.configcat.Preferences { *; }
5 | -keep class com.configcat.Setting { *; }
6 | -keep class com.configcat.SettingType { *; }
7 | -keep class com.configcat.EvaluationDetails { *; }
8 | -keep class com.configcat.TargetingRule { *; }
9 | -keep class com.configcat.SettingType { *; }
10 | -keep class com.configcat.SettingValue { *; }
11 | -keep class com.configcat.Segment { *; }
12 | -keep class com.configcat.Condition { *; }
13 | -keep class com.configcat.SimpleValue { *; }
14 | -keep class com.configcat.Condition { *; }
15 | -keep class com.configcat.UserCondition { *; }
16 | -keep class com.configcat.SegmentCondition { *; }
17 | -keep class com.configcat.PrerequisiteFlagCondition { *; }
18 | -keep class com.configcat.PercentageOption { *; }
19 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/2_targeting_rules/2_rules_not_matching_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | WARNING [3003] Cannot evaluate condition (User.Email IS ONE OF ['a@configcat.com', 'b@configcat.com']) for setting 'stringIsInDogDefaultCat' (the User.Email attribute is missing). You should set the User.Email attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'stringIsInDogDefaultCat' for User '{"Identifier":"12345","Custom1":"user"}'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email IS ONE OF ['a@configcat.com', 'b@configcat.com'] THEN 'Dog' => cannot evaluate, the User.Email attribute is missing
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | - IF User.Custom1 IS ONE OF ['admin'] THEN 'Dog' => no match
7 | Returning 'Cat'.
8 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
12 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/samples/android-kotlin/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | android.enableJetifier=true
13 | android.useAndroidX=true
14 | org.gradle.jvmargs=-Xmx1536m
15 |
16 | # When configured, Gradle will run in incubating parallel mode.
17 | # This option should only be used with decoupled projects. More details, visit
18 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
19 | # org.gradle.parallel=true
20 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/OverrideDataSource.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /**
7 | * Describes a data source for feature flag and setting overrides.
8 | */
9 | public class OverrideDataSource {
10 | /**
11 | * Gets all the overrides defined in the given source.
12 | *
13 | * @return the overrides key-setting map.
14 | */
15 | public Map getLocalConfiguration() {
16 | return new HashMap<>();
17 | }
18 |
19 | /**
20 | * Create an override data source that stores the overrides in a key-value map.
21 | *
22 | * @param map the map that holds the overrides.
23 | * @return the map based data source.
24 | */
25 | public static OverrideDataSource map(Map map) {
26 | return new LocalMapDataSource(map);
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/2_targeting_rules/2_rules_matching_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | WARNING [3003] Cannot evaluate condition (User.Email IS ONE OF ['a@configcat.com', 'b@configcat.com']) for setting 'stringIsInDogDefaultCat' (the User.Email attribute is missing). You should set the User.Email attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'stringIsInDogDefaultCat' for User '{"Identifier":"12345","Custom1":"admin"}'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email IS ONE OF ['a@configcat.com', 'b@configcat.com'] THEN 'Dog' => cannot evaluate, the User.Email attribute is missing
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | - IF User.Custom1 IS ONE OF ['admin'] THEN 'Dog' => MATCH, applying rule
7 | Returning 'Dog'.
8 |
--------------------------------------------------------------------------------
/samples/android-kotlin/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | google()
6 | mavenCentral()
7 | }
8 | dependencies {
9 | classpath 'com.android.tools.build:gradle:7.3.1'
10 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.21"
11 |
12 | // NOTE: Do not place your application dependencies here; they belong
13 | // in the individual module build.gradle files
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | google()
20 | mavenCentral()
21 | mavenLocal()
22 |
23 | maven {
24 | url "https://oss.sonatype.org/content/repositories/snapshots"
25 | }
26 | }
27 | }
28 |
29 | task clean(type: Delete) {
30 | delete rootProject.buildDir
31 | }
32 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_within_targeting_rule/options_within_targeting_rule_matching_targeted_attribute_no_options_attribute.txt:
--------------------------------------------------------------------------------
1 | WARNING [3003] Cannot evaluate % options for setting 'stringContainsString75Cat0Dog25Falcon0HorseDefaultCat' (the User.Country attribute is missing). You should set the User.Country attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'stringContainsString75Cat0Dog25Falcon0HorseDefaultCat' for User '{"Identifier":"12345","Email":"joe@configcat.com"}'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN % options => MATCH, applying rule
5 | Skipping % options because the User.Country attribute is missing.
6 | The current targeting rule is ignored and the evaluation continues with the next rule.
7 | Returning 'Cat'.
8 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/2_targeting_rules/2_rules_no_user.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'stringIsInDogDefaultCat' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'stringIsInDogDefaultCat'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email IS ONE OF ['a@configcat.com', 'b@configcat.com'] THEN 'Dog' => cannot evaluate, User Object is missing
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | - IF User.Custom1 IS ONE OF ['admin'] THEN 'Dog' => cannot evaluate, User Object is missing
7 | The current targeting rule is ignored and the evaluation continues with the next rule.
8 | Returning 'Cat'.
9 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/Condition.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | /**
6 | * Represents a condition.
7 | */
8 | public class Condition implements ConditionAccessor {
9 |
10 | @SerializedName(value = "u")
11 | private UserCondition userCondition;
12 | @SerializedName(value = "s")
13 | private SegmentCondition segmentCondition;
14 | @SerializedName(value = "p")
15 | private PrerequisiteFlagCondition prerequisiteFlagCondition;
16 |
17 | @Override
18 | public UserCondition getUserCondition() {
19 | return userCondition;
20 | }
21 |
22 | @Override
23 | public SegmentCondition getSegmentCondition() {
24 | return segmentCondition;
25 | }
26 |
27 | @Override
28 | public PrerequisiteFlagCondition getPrerequisiteFlagCondition() {
29 | return prerequisiteFlagCondition;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/LogFilterFunction.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * The Log Filter Functional Interface provides a custom filter option for the ConfigCat Logger.
5 | */
6 | @FunctionalInterface
7 | public interface LogFilterFunction {
8 |
9 | /**
10 | * Apply the custom filter option to the ConfigCatLogger.
11 | *
12 | * @param logLevel Event severity level.
13 | * @param eventId Event identifier.
14 | * @param message Message object. The formatted message String can be obtained by calling {@code toString}. (It is guaranteed that the message string is built only once even if {@code toString} called multiple times.)
15 | * @param exception The exception object related to the message (if any).
16 | * @return True to log the event, false will leave out the log.
17 | */
18 | boolean apply(LogLevel logLevel, int eventId, Object message, Throwable exception);
19 | }
20 |
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/assets/logback.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 | %logger{12}
9 |
10 |
11 | [%-20thread] %msg
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/SharedPreferencesCache.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 |
6 | /**
7 | * {@link ConfigCache} implementation that uses {@link SharedPreferences} for persistent storage.
8 | */
9 | public class SharedPreferencesCache extends ConfigCache {
10 | private final SharedPreferences sharedPreferences;
11 |
12 | public SharedPreferencesCache(android.content.Context context) {
13 | this.sharedPreferences = context.getApplicationContext().getSharedPreferences("configcat_preferences", Context.MODE_PRIVATE);
14 | }
15 |
16 | @Override
17 | protected String read(String key) {
18 | return this.sharedPreferences.getString(key, null);
19 | }
20 |
21 | @Override
22 | protected void write(String key, String value) {
23 | this.sharedPreferences.edit().putString(key, value).apply();
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/epoch_date_validation/date_error.txt:
--------------------------------------------------------------------------------
1 | WARNING [3004] Cannot evaluate condition (User.Custom1 AFTER '1680307200' (2023-04-01T00:00:00.000Z UTC)) for setting 'boolTrueIn202304' ('2023.04.10' is not a valid Unix timestamp (number of seconds elapsed since Unix epoch)). Please check the User.Custom1 attribute and make sure that its value corresponds to the comparison operator.
2 | INFO [5000] Evaluating 'boolTrueIn202304' for User '{"Identifier":"12345","Custom1":"2023.04.10"}'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Custom1 AFTER '1680307200' (2023-04-01T00:00:00.000Z UTC) => false, skipping the remaining AND conditions
5 | THEN 'true' => cannot evaluate, the User.Custom1 attribute is invalid ('2023.04.10' is not a valid Unix timestamp (number of seconds elapsed since Unix epoch))
6 | The current targeting rule is ignored and the evaluation continues with the next rule.
7 | Returning 'false'.
8 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_based_on_custom_attr.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "configcat-sdk-1/JcPbCGl_1E-K9M-fJOyKyQ/P4e3fAz_1ky2-Zg2e4cbkw",
3 | "tests": [
4 | {
5 | "key": "string75Cat0Dog25Falcon0HorseCustomAttr",
6 | "defaultValue": "default",
7 | "returnValue": "Chicken",
8 | "expectedLog": "options_custom_attribute_no_user.txt"
9 | },
10 | {
11 | "key": "string75Cat0Dog25Falcon0HorseCustomAttr",
12 | "defaultValue": "default",
13 | "user": {
14 | "Identifier": "12345"
15 | },
16 | "returnValue": "Chicken",
17 | "expectedLog": "no_options_custom_attribute.txt"
18 | },
19 | {
20 | "key": "string75Cat0Dog25Falcon0HorseCustomAttr",
21 | "defaultValue": "default",
22 | "user": {
23 | "Identifier": "12345",
24 | "Country": "US"
25 | },
26 | "returnValue": "Cat",
27 | "expectedLog": "matching_options_custom_attribute.txt"
28 | }
29 | ]
30 | }
31 |
--------------------------------------------------------------------------------
/src/test/resources/matrix/testmatrix_prerequisite_flag.csv:
--------------------------------------------------------------------------------
1 | Identifier;Email;Country;Custom1;mainBoolFlag;mainStringFlag;mainIntFlag;mainDoubleFlag;stringDependsOnBool;stringDependsOnString;stringDependsOnStringCaseCheck;stringDependsOnInt;stringDependsOnDouble;stringDependsOnDoubleIntValue;boolDependsOnBool;intDependsOnBool;doubleDependsOnBool;boolDependsOnBoolDependsOnBool;mainBoolFlagEmpty;stringDependsOnEmptyBool;stringInverseDependsOnEmptyBool;mainBoolFlagInverse;boolDependsOnBoolInverse
2 | ##null##;;;;True;public;42;3.14;Dog;Cat;Cat;Cat;Cat;Cat;True;1;1.1;False;True;EmptyOn;EmptyOn;False;True
3 | ;;;;True;public;42;3.14;Dog;Cat;Cat;Cat;Cat;Cat;True;1;1.1;False;True;EmptyOn;EmptyOn;False;True
4 | john@sensitivecompany.com;john@sensitivecompany.com;##null##;##null##;False;private;2;0.1;Cat;Dog;Cat;Dog;Dog;Cat;False;42;3.14;True;True;EmptyOn;EmptyOn;True;False
5 | jane@example.com;jane@example.com;##null##;##null##;True;public;42;3.14;Dog;Cat;Cat;Cat;Cat;Cat;True;1;1.1;False;True;EmptyOn;EmptyOn;False;True
6 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/simple_value.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "PKDVCLf-Hq-h-kCzMp-L7Q/psuH7BGHoUmdONrzzUOY7A",
3 | "tests": [
4 | {
5 | "key": "boolDefaultFalse",
6 | "defaultValue": true,
7 | "returnValue": false,
8 | "expectedLog": "off_flag.txt"
9 | },
10 | {
11 | "key": "boolDefaultTrue",
12 | "defaultValue": false,
13 | "returnValue": true,
14 | "expectedLog": "on_flag.txt"
15 | },
16 | {
17 | "key": "stringDefaultCat",
18 | "defaultValue": "Default",
19 | "returnValue": "Cat",
20 | "expectedLog": "text_setting.txt"
21 | },
22 | {
23 | "key": "integerDefaultOne",
24 | "defaultValue": 0,
25 | "returnValue": 1,
26 | "expectedLog": "int_setting.txt"
27 | },
28 | {
29 | "testName": "double_setting",
30 | "key": "doubleDefaultPi",
31 | "defaultValue": 0.0,
32 | "returnValue": 3.1415,
33 | "expectedLog": "double_setting.txt"
34 | }
35 | ]
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/ConfigCache.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * A cache API used to make custom cache implementations for {@link ConfigCatClient}.
5 | */
6 | public abstract class ConfigCache {
7 | /**
8 | * Child classes has to implement this method, the {@link ConfigCatClient}
9 | * uses it to get the actual value from the cache.
10 | *
11 | * @param key the key of the cache entry.
12 | * @return the cached configuration.
13 | * @throws Exception if unable to read the cache.
14 | */
15 | protected abstract String read(String key) throws Exception;
16 |
17 | /**
18 | * * Child classes has to implement this method, the {@link ConfigCatClient}
19 | * uses it to set the actual cached value.
20 | *
21 | * @param key the key of the cache entry.
22 | * @param value the new value to cache.
23 | * @throws Exception if unable to save the value.
24 | */
25 | protected abstract void write(String key, String value) throws Exception;
26 | }
27 |
28 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/DateTimeUtils.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 |
4 | import java.text.SimpleDateFormat;
5 | import java.util.Date;
6 | import java.util.TimeZone;
7 |
8 | public class DateTimeUtils {
9 |
10 | private DateTimeUtils() { /* prevent from instantiation*/ }
11 |
12 | public static boolean isValidDate(String date) {
13 | try {
14 | Long.parseLong(date);
15 | } catch (NumberFormatException e) {
16 | return false;
17 | }
18 | return true;
19 | }
20 |
21 | public static String doubleToFormattedUTC(double dateInDouble) {
22 | long dateInMilliSec = (long) dateInDouble * 1000;
23 | SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
24 | simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
25 | return simpleDateFormat.format(new Date(dateInMilliSec));
26 | }
27 |
28 | public static double getUnixSeconds(Date date) {
29 | return date.getTime() / 1000d;
30 | }
31 | }
--------------------------------------------------------------------------------
/samples/android-java/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | google()
6 | mavenCentral()
7 | }
8 | dependencies {
9 | classpath 'com.android.tools.build:gradle:7.3.1'
10 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.21"
11 |
12 | // NOTE: Do not place your application dependencies here; they belong
13 | // in the individual module build.gradle files
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | google()
20 | mavenCentral()
21 | mavenLocal()
22 |
23 | maven {
24 | url "https://oss.sonatype.org/content/repositories/snapshots"
25 | }
26 | }
27 | }
28 |
29 | //plugins {
30 | // id 'com.android.application' version '7.3.1' apply false
31 | // id 'com.android.library' version '7.3.1' apply false
32 | //}
33 |
34 | task clean(type: Delete) {
35 | delete rootProject.buildDir
36 | }
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_after_targeting_rule/options_after_targeting_rule_no_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | WARNING [3003] Cannot evaluate condition (User.Email CONTAINS ANY OF ['@configcat.com']) for setting 'integer25One25Two25Three25FourAdvancedRules' (the User.Email attribute is missing). You should set the User.Email attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'integer25One25Two25Three25FourAdvancedRules' for User '{"Identifier":"12345"}'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email CONTAINS ANY OF ['@configcat.com'] THEN '5' => cannot evaluate, the User.Email attribute is missing
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | Evaluating % options based on the User.Identifier attribute:
7 | - Computing hash in the [0..99] range from User.Identifier => 25 (this value is sticky and consistent across all SDKs)
8 | - Hash value 25 selects % option 2 (25%), '2'.
9 | Returning '2'.
10 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/PercentageOption.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | /**
6 | * Represents a percentage option.
7 | */
8 | public class PercentageOption {
9 |
10 | @SerializedName(value = "p")
11 | private int percentage;
12 | @SerializedName(value = "v")
13 | private SettingValue value;
14 | @SerializedName(value = "i")
15 | private String variationId;
16 |
17 | /**
18 | * A number between 0 and 100 that represents a randomly allocated fraction of the users.
19 | */
20 | public int getPercentage() {
21 | return percentage;
22 | }
23 |
24 | /**
25 | * The value associated with the percentage option.
26 | * Can be a value of the following types: {@link Boolean}, {@link String}, {@link Integer} or {@link Double}.
27 | */
28 | public SettingValue getValue() {
29 | return value;
30 | }
31 |
32 | /**
33 | * Variation ID.
34 | */
35 | public String getVariationId() {
36 | return variationId;
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/SegmentComparator.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * Segment comparison operator used during the evaluation process.
5 | */
6 | public enum SegmentComparator {
7 |
8 | /**
9 | * IS IN SEGMENT - Checks whether the conditions of the specified segment are evaluated to true.
10 | */
11 | IS_IN_SEGMENT(0, "IS IN SEGMENT"),
12 | /**
13 | * IS NOT IN SEGMENT - Checks whether the conditions of the specified segment are evaluated to false.
14 | */
15 | IS_NOT_IN_SEGMENT(1, "IS NOT IN SEGMENT");
16 |
17 | private final int id;
18 | private final String name;
19 |
20 | SegmentComparator(int id, String name) {
21 | this.id = id;
22 | this.name = name;
23 | }
24 |
25 | public String getName() {
26 | return name;
27 | }
28 |
29 | public static SegmentComparator fromId(int id) {
30 | for (SegmentComparator comparator : SegmentComparator.values()) {
31 | if (comparator.id == id) {
32 | return comparator;
33 | }
34 | }
35 | return null;
36 | }
37 |
38 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 ConfigCat
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/test/resources/matrix/testmatrix_and_or.csv:
--------------------------------------------------------------------------------
1 | Identifier;Email;Country;Custom1;mainFeature;dependentFeature;emailAnd;emailOr
2 | ##null##;;;;public;Chicken;Cat;Cat
3 | ;;;;public;Chicken;Cat;Cat
4 | jane@example.com;jane@example.com;##null##;##null##;public;Chicken;Cat;Jane
5 | john@example.com;john@example.com;##null##;##null##;public;Chicken;Cat;John
6 | a@example.com;a@example.com;USA;##null##;target;Cat;Cat;Cat
7 | mark@example.com;mark@example.com;USA;##null##;target;Dog;Cat;Mark
8 | nora@example.com;nora@example.com;USA;##null##;target;Falcon;Cat;Cat
9 | stern@msn.com;stern@msn.com;USA;##null##;target;Horse;Cat;Cat
10 | jane@sensitivecompany.com;jane@sensitivecompany.com;England;##null##;private;Chicken;Dog;Jane
11 | anna@sensitivecompany.com;anna@sensitivecompany.com;France;##null##;private;Chicken;Cat;Cat
12 | jane@sensitivecompany.com;jane@sensitivecompany.com;england;##null##;public;Chicken;Dog;Jane
13 | jane;jane;##null##;##null##;public;Chicken;Cat;Cat
14 | @sensitivecompany.com;@sensitivecompany.com;##null##;##null##;public;Chicken;Cat;Cat
15 | jane.sensitivecompany.com;jane.sensitivecompany.com;##null##;##null##;public;Chicken;Cat;Cat
16 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/PrerequisiteComparator.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * Prerequisite flag comparison operator used during the evaluation process.
5 | */
6 | public enum PrerequisiteComparator {
7 | /**
8 | * EQUALS - Checks whether the evaluated value of the specified prerequisite flag is equal to the comparison value.
9 | */
10 | EQUALS(0, "EQUALS"),
11 | /**
12 | * NOT EQUALS - Checks whether the evaluated value of the specified prerequisite flag is not equal to the comparison value.
13 | */
14 | NOT_EQUALS(1, "NOT EQUALS");
15 |
16 | private final int id;
17 | private final String name;
18 |
19 | PrerequisiteComparator(int id, String name) {
20 | this.id = id;
21 | this.name = name;
22 | }
23 |
24 | public String getName() {
25 | return name;
26 | }
27 |
28 | public static PrerequisiteComparator fromId(int id) {
29 | for (PrerequisiteComparator comparator : PrerequisiteComparator.values()) {
30 | if (comparator.id == id) {
31 | return comparator;
32 | }
33 | }
34 | return null;
35 | }
36 |
37 | }
--------------------------------------------------------------------------------
/src/test/resources/evaluation/2_targeting_rules.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "PKDVCLf-Hq-h-kCzMp-L7Q/psuH7BGHoUmdONrzzUOY7A",
3 | "tests": [
4 | {
5 | "key": "stringIsInDogDefaultCat",
6 | "defaultValue": "default",
7 | "returnValue": "Cat",
8 | "expectedLog": "2_rules_no_user.txt"
9 | },
10 | {
11 | "key": "stringIsInDogDefaultCat",
12 | "defaultValue": "default",
13 | "user": {
14 | "Identifier": "12345"
15 | },
16 | "returnValue": "Cat",
17 | "expectedLog": "2_rules_no_targeted_attribute.txt"
18 | },
19 | {
20 | "key": "stringIsInDogDefaultCat",
21 | "defaultValue": "default",
22 | "user": {
23 | "Identifier": "12345",
24 | "Custom1": "user"
25 | },
26 | "returnValue": "Cat",
27 | "expectedLog": "2_rules_not_matching_targeted_attribute.txt"
28 | },
29 | {
30 | "key": "stringIsInDogDefaultCat",
31 | "defaultValue": "default",
32 | "user": {
33 | "Identifier": "12345",
34 | "Custom1": "admin"
35 | },
36 | "returnValue": "Dog",
37 | "expectedLog": "2_rules_matching_targeted_attribute.txt"
38 | }
39 | ]
40 | }
41 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/segment/segment_no_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | WARNING [3003] Cannot evaluate condition (User.Email IS ONE OF ['jane@example.com', 'john@example.com']) for setting 'featureWithNegatedSegmentTargetingCleartext' (the User.Email attribute is missing). You should set the User.Email attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'featureWithNegatedSegmentTargetingCleartext' for User '{"Identifier":"12345"}'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User IS NOT IN SEGMENT 'Beta users (cleartext)'
5 | (
6 | Evaluating segment 'Beta users (cleartext)':
7 | - IF User.Email IS ONE OF ['jane@example.com', 'john@example.com'] => false, skipping the remaining AND conditions
8 | Segment evaluation result: cannot evaluate, the User.Email attribute is missing.
9 | Condition (User IS NOT IN SEGMENT 'Beta users (cleartext)') failed to evaluate.
10 | )
11 | THEN 'true' => cannot evaluate, the User.Email attribute is missing
12 | The current targeting rule is ignored and the evaluation continues with the next rule.
13 | Returning 'false'.
14 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/FormattableLogMessage.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import org.jetbrains.annotations.NotNull;
4 |
5 | import java.util.Arrays;
6 | import java.util.Objects;
7 |
8 | class FormattableLogMessage {
9 |
10 | private String cachedMessage;
11 | protected final String message;
12 | protected final Object[] args;
13 |
14 | FormattableLogMessage(String message, Object... args) {
15 | this.message = message;
16 | this.args = args;
17 | }
18 |
19 | protected String formatLogMessage(){
20 | return String.format(message, args);
21 | }
22 |
23 | @NotNull
24 | @Override
25 | public String toString() {
26 | if(cachedMessage == null) {
27 | cachedMessage = formatLogMessage();
28 | }
29 | return cachedMessage;
30 | }
31 |
32 |
33 | @Override
34 | public boolean equals(Object obj) {
35 | if(obj instanceof FormattableLogMessage) {
36 | return toString().equals(obj.toString());
37 | }
38 | return false;
39 | }
40 |
41 | @Override
42 | public int hashCode() {
43 | return Objects.hash(cachedMessage, message, Arrays.hashCode(args));
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
13 |
18 |
19 |
20 |
21 |
22 |
23 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/FormattableLogMessageWithKeySet.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import java.util.Iterator;
4 | import java.util.Set;
5 |
6 | class FormattableLogMessageWithKeySet extends FormattableLogMessage {
7 |
8 | FormattableLogMessageWithKeySet(String message, Object... args) {
9 | super(message,args);
10 | }
11 |
12 | @Override
13 | protected String formatLogMessage() {
14 | Object keySetObject = args[args.length - 1];
15 | if(keySetObject instanceof Set) {
16 | Set keySet = (Set) keySetObject;
17 | args[args.length - 1] = convertKeySetToFormattedString(keySet);
18 | }
19 | return String.format(message, args);
20 | }
21 |
22 | private static String convertKeySetToFormattedString(final Set availableKeys) {
23 | StringBuilder sb = new StringBuilder();
24 | Iterator it = availableKeys.iterator();
25 | if (it.hasNext()) {
26 | sb.append("'").append(it.next()).append("'");
27 | }
28 | while (it.hasNext()) {
29 | sb.append(", ").append("'").append(it.next()).append("'");
30 | }
31 | return sb.toString();
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/1_targeting_rule.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "PKDVCLf-Hq-h-kCzMp-L7Q/psuH7BGHoUmdONrzzUOY7A",
3 | "tests": [
4 | {
5 | "key": "stringContainsDogDefaultCat",
6 | "defaultValue": "default",
7 | "returnValue": "Cat",
8 | "expectedLog": "1_rule_no_user.txt"
9 | },
10 | {
11 | "key": "stringContainsDogDefaultCat",
12 | "defaultValue": "default",
13 | "user": {
14 | "Identifier": "12345"
15 | },
16 | "returnValue": "Cat",
17 | "expectedLog": "1_rule_no_targeted_attribute.txt"
18 | },
19 | {
20 | "key": "stringContainsDogDefaultCat",
21 | "defaultValue": "default",
22 | "user": {
23 | "Identifier": "12345",
24 | "Email": "joe@example.com"
25 | },
26 | "returnValue": "Cat",
27 | "expectedLog": "1_rule_not_matching_targeted_attribute.txt"
28 | },
29 | {
30 | "key": "stringContainsDogDefaultCat",
31 | "defaultValue": "default",
32 | "user": {
33 | "Identifier": "12345",
34 | "Email": "joe@configcat.com"
35 | },
36 | "returnValue": "Dog",
37 | "expectedLog": "1_rule_matching_targeted_attribute.txt"
38 | }
39 | ]
40 | }
41 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/prerequisite_flag/prerequisite_flag_no_user_needed_by_dep.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'dependentFeatureWithUserCondition' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'dependentFeatureWithUserCondition'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF User.Email IS ONE OF [<2 hashed values>] THEN 'Dog' => cannot evaluate, User Object is missing
5 | The current targeting rule is ignored and the evaluation continues with the next rule.
6 | - IF Flag 'mainFeatureWithoutUserCondition' EQUALS 'true'
7 | (
8 | Evaluating prerequisite flag 'mainFeatureWithoutUserCondition':
9 | Prerequisite flag evaluation result: 'true'.
10 | Condition (Flag 'mainFeatureWithoutUserCondition' EQUALS 'true') evaluates to true.
11 | )
12 | THEN % options => MATCH, applying rule
13 | Skipping % options because the User Object is missing.
14 | The current targeting rule is ignored and the evaluation continues with the next rule.
15 | Returning 'Chicken'.
16 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/OverrideBehaviour.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * Describes how the overrides should behave.
5 | */
6 | public enum OverrideBehaviour {
7 | /**
8 | * When evaluating values, the SDK will not use feature flags and settings from the ConfigCat CDN, but it will use
9 | * all feature flags and settings that are loaded from local-override sources.
10 | */
11 | LOCAL_ONLY,
12 | /**
13 | * When evaluating values, the SDK will use all feature flags and settings that are downloaded from the ConfigCat CDN,
14 | * plus all feature flags and settings that are loaded from local-override sources. If a feature flag or a setting is
15 | * defined both in the fetched and the local-override source then the local-override version will take precedence.
16 | */
17 | LOCAL_OVER_REMOTE,
18 | /**
19 | * When evaluating values, the SDK will use all feature flags and settings that are downloaded from the ConfigCat CDN,
20 | * plus all feature flags and settings that are loaded from local-override sources. If a feature flag or a setting is
21 | * defined both in the fetched and the local-override source then the fetched version will take precedence.
22 | */
23 | REMOTE_OVER_LOCAL,
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/PrerequisiteFlagCondition.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | /**
6 | * Describes a condition that is based on a prerequisite flag.
7 | */
8 | public class PrerequisiteFlagCondition {
9 |
10 | @SerializedName(value = "f")
11 | private String prerequisiteFlagKey;
12 | @SerializedName(value = "c")
13 | private int prerequisiteComparator;
14 | @SerializedName(value = "v")
15 | private SettingValue value;
16 |
17 | /**
18 | * The key of the prerequisite flag that the condition is based on.
19 | */
20 | public String getPrerequisiteFlagKey() {
21 | return prerequisiteFlagKey;
22 | }
23 |
24 | /**
25 | * The operator which defines the relation between the evaluated value of the prerequisite flag and the comparison value.
26 | */
27 | public int getPrerequisiteComparator() {
28 | return prerequisiteComparator;
29 | }
30 |
31 | /**
32 | * The value that the evaluated value of the prerequisite flag is compared to.
33 | * Can be a value of the following types: {@link Boolean}, {@link String}, {@link Integer} or {@link Double}.
34 | */
35 | public SettingValue getValue() {
36 | return value;
37 | }
38 | }
--------------------------------------------------------------------------------
/src/test/java/com/configcat/TestCache.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import java.util.HashMap;
4 |
5 | class FailingCache extends ConfigCache {
6 |
7 | @Override
8 | protected String read(String key) throws Exception {
9 | throw new Exception();
10 | }
11 |
12 | @Override
13 | protected void write(String key, String value) throws Exception {
14 | throw new Exception();
15 | }
16 | }
17 |
18 | class SingleValueCache extends ConfigCache {
19 | private String value;
20 |
21 | public SingleValueCache(String value) {
22 | this.value = value;
23 | }
24 |
25 | @Override
26 | protected String read(String key) {
27 | return this.value;
28 | }
29 |
30 | @Override
31 | protected void write(String key, String value) {
32 | this.value = value;
33 | }
34 | }
35 |
36 | class InMemoryCache extends ConfigCache {
37 | HashMap map = new HashMap<>();
38 |
39 | @Override
40 | protected String read(String key) {
41 | return map.get(key);
42 | }
43 |
44 | @Override
45 | protected void write(String key, String value) {
46 | this.map.put(key, value);
47 | }
48 |
49 | public HashMap getMap() {
50 | return map;
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/2_targeting_rules/2_rules_no_targeted_attribute.txt:
--------------------------------------------------------------------------------
1 | WARNING [3003] Cannot evaluate condition (User.Email IS ONE OF ['a@configcat.com', 'b@configcat.com']) for setting 'stringIsInDogDefaultCat' (the User.Email attribute is missing). You should set the User.Email attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | WARNING [3003] Cannot evaluate condition (User.Custom1 IS ONE OF ['admin']) for setting 'stringIsInDogDefaultCat' (the User.Custom1 attribute is missing). You should set the User.Custom1 attribute in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
3 | INFO [5000] Evaluating 'stringIsInDogDefaultCat' for User '{"Identifier":"12345"}'
4 | Evaluating targeting rules and applying the first match if any:
5 | - IF User.Email IS ONE OF ['a@configcat.com', 'b@configcat.com'] THEN 'Dog' => cannot evaluate, the User.Email attribute is missing
6 | The current targeting rule is ignored and the evaluation continues with the next rule.
7 | - IF User.Custom1 IS ONE OF ['admin'] THEN 'Dog' => cannot evaluate, the User.Custom1 attribute is missing
8 | The current targeting rule is ignored and the evaluation continues with the next rule.
9 | Returning 'Cat'.
10 |
--------------------------------------------------------------------------------
/samples/android-java/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | }
4 |
5 | android {
6 | namespace 'com.configcat.configcatsample'
7 | compileSdk 32
8 |
9 | defaultConfig {
10 | applicationId "com.configcat.configcatsample"
11 | minSdk 21
12 | targetSdk 32
13 | versionCode 1
14 | versionName "1.0"
15 |
16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 | }
18 |
19 | buildTypes {
20 | release {
21 | minifyEnabled false
22 | }
23 | }
24 | compileOptions {
25 | // Sets Java compatibility to Java 8
26 | sourceCompatibility JavaVersion.VERSION_1_8
27 | targetCompatibility JavaVersion.VERSION_1_8
28 | }
29 | buildFeatures {
30 | viewBinding true
31 | }
32 | }
33 |
34 | dependencies {
35 | implementation 'androidx.appcompat:appcompat:1.5.1'
36 | implementation 'androidx.lifecycle:lifecycle-viewmodel:2.4.0'
37 | implementation 'com.google.android.material:material:1.5.0'
38 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
39 | implementation 'com.configcat:configcat-android-client:10.0.0'
40 | implementation 'org.slf4j:slf4j-api:2.0.7'
41 | implementation 'com.github.tony19:logback-android:3.0.0'
42 | }
--------------------------------------------------------------------------------
/src/test/resources/evaluation/prerequisite_flag.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "configcat-sdk-1/JcPbCGl_1E-K9M-fJOyKyQ/ByMO9yZNn02kXcm72lnY1A",
3 | "tests": [
4 | {
5 | "key": "dependentFeatureWithUserCondition",
6 | "defaultValue": "default",
7 | "returnValue": "Chicken",
8 | "expectedLog": "prerequisite_flag_no_user_needed_by_dep.txt"
9 | },
10 | {
11 | "key": "dependentFeature",
12 | "defaultValue": "default",
13 | "returnValue": "Chicken",
14 | "expectedLog": "prerequisite_flag_no_user_needed_by_prereq.txt"
15 | },
16 | {
17 | "key": "dependentFeatureWithUserCondition2",
18 | "defaultValue": "default",
19 | "returnValue": "Frog",
20 | "expectedLog": "prerequisite_flag_no_user_needed_by_both.txt"
21 | },
22 | {
23 | "key": "dependentFeature",
24 | "defaultValue": "default",
25 | "user": {
26 | "Identifier": "12345",
27 | "Email": "kate@configcat.com",
28 | "Country": "USA"
29 | },
30 | "returnValue": "Horse",
31 | "expectedLog": "prerequisite_flag.txt"
32 | },
33 | {
34 | "key": "dependentFeatureMultipleLevels",
35 | "defaultValue": "default",
36 | "returnValue": "Dog",
37 | "expectedLog": "prerequisite_flag_multilevel.txt"
38 | }
39 | ]
40 | }
41 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/prerequisite_flag/prerequisite_flag_multilevel.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'dependentFeatureMultipleLevels'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF Flag 'intermediateFeature' EQUALS 'true'
4 | (
5 | Evaluating prerequisite flag 'intermediateFeature':
6 | Evaluating targeting rules and applying the first match if any:
7 | - IF Flag 'mainFeatureWithoutUserCondition' EQUALS 'true'
8 | (
9 | Evaluating prerequisite flag 'mainFeatureWithoutUserCondition':
10 | Prerequisite flag evaluation result: 'true'.
11 | Condition (Flag 'mainFeatureWithoutUserCondition' EQUALS 'true') evaluates to true.
12 | ) => true
13 | AND Flag 'mainFeatureWithoutUserCondition' EQUALS 'true'
14 | (
15 | Evaluating prerequisite flag 'mainFeatureWithoutUserCondition':
16 | Prerequisite flag evaluation result: 'true'.
17 | Condition (Flag 'mainFeatureWithoutUserCondition' EQUALS 'true') evaluates to true.
18 | ) => true
19 | THEN 'true' => MATCH, applying rule
20 | Prerequisite flag evaluation result: 'true'.
21 | Condition (Flag 'intermediateFeature' EQUALS 'true') evaluates to true.
22 | )
23 | THEN 'Dog' => MATCH, applying rule
24 | Returning 'Dog'.
25 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/Config.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | import java.util.HashMap;
6 | import java.util.Map;
7 |
8 | /**
9 | * Details of a ConfigCat config.
10 | */
11 | public class Config {
12 |
13 | @SerializedName(value = "p")
14 | private Preferences preferences;
15 | @SerializedName(value = "f")
16 | private Map entries = new HashMap<>();
17 | @SerializedName(value = "s")
18 | private Segment[] segments;
19 |
20 | /**
21 | * The config preferences.
22 | */
23 | public Preferences getPreferences() {
24 | return preferences;
25 | }
26 |
27 | /**
28 | * The list of segments.
29 | */
30 | public Segment[] getSegments() {
31 | return segments;
32 | }
33 |
34 | /**
35 | * The map of settings.
36 | */
37 | public Map getEntries() {
38 | // NOTE: Deserializing a JSON like '{ "f": null }' overwrites entries with null.
39 | // However, we want to treat null as an empty map in that case too.
40 | return entries != null ? entries : (entries = new HashMap<>());
41 | }
42 |
43 | boolean isEmpty() {
44 | return EMPTY.equals(this);
45 | }
46 |
47 | public static final Config EMPTY = new Config();
48 | }
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_after_targeting_rule.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "PKDVCLf-Hq-h-kCzMp-L7Q/psuH7BGHoUmdONrzzUOY7A",
3 | "tests": [
4 | {
5 | "key": "integer25One25Two25Three25FourAdvancedRules",
6 | "defaultValue": 42,
7 | "returnValue": -1,
8 | "expectedLog": "options_after_targeting_rule_no_user.txt"
9 | },
10 | {
11 | "key": "integer25One25Two25Three25FourAdvancedRules",
12 | "defaultValue": 42,
13 | "user": {
14 | "Identifier": "12345"
15 | },
16 | "returnValue": 2,
17 | "expectedLog": "options_after_targeting_rule_no_targeted_attribute.txt"
18 | },
19 | {
20 | "key": "integer25One25Two25Three25FourAdvancedRules",
21 | "defaultValue": 42,
22 | "user": {
23 | "Identifier": "12345",
24 | "Email": "joe@example.com"
25 | },
26 | "returnValue": 2,
27 | "expectedLog": "options_after_targeting_rule_not_matching_targeted_attribute.txt"
28 | },
29 | {
30 | "key": "integer25One25Two25Three25FourAdvancedRules",
31 | "defaultValue": 42,
32 | "user": {
33 | "Identifier": "12345",
34 | "Email": "joe@configcat.com"
35 | },
36 | "returnValue": 5,
37 | "expectedLog": "options_after_targeting_rule_matching_targeted_attribute.txt"
38 | }
39 | ]
40 | }
41 |
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
17 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/samples/android-java/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Enables namespacing of each library's R class so that its R class includes only the
19 | # resources declared in the library itself and none from the library's dependencies,
20 | # thereby reducing the size of the R class for that library
21 | android.nonTransitiveRClass=true
--------------------------------------------------------------------------------
/src/test/java/com/configcat/UserTests.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | class UserTests {
8 |
9 | @Test
10 | void builderWorksWithEmptyOrNullId() {
11 | User u1 = User.newBuilder().build(null);
12 | assertEquals("", u1.getIdentifier());
13 | User u2 = User.newBuilder().build("");
14 | assertEquals("", u2.getIdentifier());
15 | }
16 |
17 | @Test
18 | void getAttributeThrowsWhenArgumentInvalid() {
19 | User user = User.newBuilder().build("a");
20 | assertThrows(IllegalArgumentException.class, () -> user.getAttribute(null));
21 | assertNull(user.getAttribute(""));
22 | }
23 |
24 | @Test
25 | void getAttributeCaseSensitivityTest() {
26 | String email = "a@a.com";
27 | String country = "b";
28 | User user = User.newBuilder().email(email).country("b").build("a");
29 | assertEquals(email, user.getAttribute("Email"));
30 | assertNotEquals(email, user.getAttribute("EMAIL"));
31 | assertNotEquals(email, user.getAttribute("email"));
32 |
33 | assertEquals(country, user.getAttribute("Country"));
34 | assertNotEquals(country, user.getAttribute("COUNTRY"));
35 | assertNotEquals(country, user.getAttribute("country"));
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/segment.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "configcat-sdk-1/PKDVCLf-Hq-h-kCzMp-L7Q/y_ZB7o-Xb0Swxth-ZlMSeA",
3 | "tests": [
4 | {
5 | "key": "featureWithSegmentTargeting",
6 | "defaultValue": false,
7 | "returnValue": false,
8 | "expectedLog": "segment_no_user.txt"
9 | },
10 | {
11 | "key": "featureWithNegatedSegmentTargetingCleartext",
12 | "defaultValue": false,
13 | "user": {
14 | "Identifier": "12345"
15 | },
16 | "returnValue": false,
17 | "expectedLog": "segment_no_targeted_attribute.txt"
18 | },
19 | {
20 | "key": "featureWithSegmentTargeting",
21 | "defaultValue": false,
22 | "user": {
23 | "Identifier": "12345",
24 | "Email": "jane@example.com"
25 | },
26 | "returnValue": true,
27 | "expectedLog": "segment_matching.txt"
28 | },
29 | {
30 | "key": "featureWithNegatedSegmentTargeting",
31 | "defaultValue": false,
32 | "user": {
33 | "Identifier": "12345",
34 | "Email": "jane@example.com"
35 | },
36 | "returnValue": false,
37 | "expectedLog": "segment_no_matching.txt"
38 | },
39 | {
40 | "key": "featureWithSegmentTargetingMultipleConditions",
41 | "defaultValue": false,
42 | "returnValue": false,
43 | "expectedLog": "segment_no_user_multi_conditions.txt"
44 | }
45 | ]
46 | }
47 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/prerequisite_flag/prerequisite_flag_no_user_needed_by_prereq.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'mainFeature' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | INFO [5000] Evaluating 'dependentFeature'
3 | Evaluating targeting rules and applying the first match if any:
4 | - IF Flag 'mainFeature' EQUALS 'target'
5 | (
6 | Evaluating prerequisite flag 'mainFeature':
7 | Evaluating targeting rules and applying the first match if any:
8 | - IF User.Email ENDS WITH ANY OF [<1 hashed value>] => false, skipping the remaining AND conditions
9 | THEN 'private' => cannot evaluate, User Object is missing
10 | The current targeting rule is ignored and the evaluation continues with the next rule.
11 | - IF User.Country IS ONE OF [<1 hashed value>] => false, skipping the remaining AND conditions
12 | THEN 'target' => cannot evaluate, User Object is missing
13 | The current targeting rule is ignored and the evaluation continues with the next rule.
14 | Prerequisite flag evaluation result: 'public'.
15 | Condition (Flag 'mainFeature' EQUALS 'target') evaluates to false.
16 | )
17 | THEN % options => no match
18 | Returning 'Chicken'.
19 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/semver_validation/semver_error.txt:
--------------------------------------------------------------------------------
1 | WARNING [3004] Cannot evaluate condition (User.Custom1 IS NOT ONE OF ['1.0.0', '1.0.1', '2.0.0', '2.0.1', '2.0.2', '']) for setting 'isNotOneOf' ('wrong_semver' is not a valid semantic version). Please check the User.Custom1 attribute and make sure that its value corresponds to the comparison operator.
2 | WARNING [3004] Cannot evaluate condition (User.Custom1 IS NOT ONE OF ['1.0.0', '3.0.1']) for setting 'isNotOneOf' ('wrong_semver' is not a valid semantic version). Please check the User.Custom1 attribute and make sure that its value corresponds to the comparison operator.
3 | INFO [5000] Evaluating 'isNotOneOf' for User '{"Identifier":"12345","Custom1":"wrong_semver"}'
4 | Evaluating targeting rules and applying the first match if any:
5 | - IF User.Custom1 IS NOT ONE OF ['1.0.0', '1.0.1', '2.0.0', '2.0.1', '2.0.2', ''] THEN 'Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, )' => cannot evaluate, the User.Custom1 attribute is invalid ('wrong_semver' is not a valid semantic version)
6 | The current targeting rule is ignored and the evaluation continues with the next rule.
7 | - IF User.Custom1 IS NOT ONE OF ['1.0.0', '3.0.1'] THEN 'Is not one of (1.0.0, 3.0.1)' => cannot evaluate, the User.Custom1 attribute is invalid ('wrong_semver' is not a valid semantic version)
8 | The current targeting rule is ignored and the evaluation continues with the next rule.
9 | Returning 'Default'.
10 |
--------------------------------------------------------------------------------
/DEPLOY.md:
--------------------------------------------------------------------------------
1 | # Steps to deploy
2 | ## Preparation
3 | 1. Run tests
4 | 3. Increase the version in the `gradle.properties` and `src/main/java/com.configcat/Utils.java` file.
5 | 4. Commit & Push
6 | ## Publish
7 | Use the **same version** for the git tag as in the properties file.
8 | - Via git tag
9 | 1. Create a new version tag.
10 | ```bash
11 | git tag v[MAJOR].[MINOR].[PATCH]
12 | ```
13 | > Example: `git tag v2.5.5`
14 | 2. Push the tag.
15 | ```bash
16 | git push origin --tags
17 | ```
18 | - Via Github release
19 |
20 | Create a new [Github release](https://github.com/configcat/android-sdk/releases) with a new version tag and release notes.
21 |
22 | ## Sync
23 |
24 | 1. Log in to [Maven Central Repository](https://central.sonatype.org/) and follow these steps:
25 | 1. Go to the `Publish` page and select the version you published.
26 | 2. Click `Publish`. The process might take some time, click `Refresh` to get the latest state.
27 | 2. Make sure the new version is available on [Maven Central](https://central.sonatype.com/artifact/com.configcat/configcat-android-client).
28 |
29 | ## Update import examples in local README.md
30 |
31 | ## Update code examples in ConfigCat Dashboard project's
32 | `steps to connect your application`
33 | 1. Update Maven import examples.
34 | 2. Update Gradle import examples.
35 |
36 | ## Update import examples in Docs
37 |
38 | ## Update samples
39 | Update and test sample apps with the new SDK version.
--------------------------------------------------------------------------------
/samples/android-kotlin/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | apply plugin: 'kotlin-android'
4 |
5 | android {
6 | buildFeatures {
7 | viewBinding true
8 | }
9 | compileSdkVersion 32
10 | defaultConfig {
11 | applicationId "com.configcat.configcatsample"
12 | minSdkVersion 21
13 | targetSdkVersion 32
14 | versionCode 1
15 | versionName "1.0"
16 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
17 | }
18 | buildTypes {
19 | release {
20 | minifyEnabled true
21 | shrinkResources true
22 | proguardFiles getDefaultProguardFile(
23 | 'proguard-android-optimize.txt'),
24 | 'proguard-rules.pro'
25 | }
26 | }
27 |
28 | compileOptions {
29 | sourceCompatibility JavaVersion.VERSION_1_8
30 | targetCompatibility JavaVersion.VERSION_1_8
31 | }
32 | }
33 |
34 | dependencies {
35 | implementation fileTree(dir: 'libs', include: ['*.jar'])
36 | implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.7.21'
37 | implementation 'androidx.appcompat:appcompat:1.5.1'
38 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
39 | implementation 'com.configcat:configcat-android-client:10.0.0'
40 | implementation 'com.noveogroup.android:android-logger:1.3.1'
41 | testImplementation 'junit:junit:4.13.2'
42 | androidTestImplementation 'androidx.test.ext:junit:1.1.4'
43 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/EvaluationContext.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import java.util.List;
4 | import java.util.Map;
5 |
6 | class EvaluationContext {
7 | public EvaluationContext(String key, User user, List visitedKeys, Map settings) {
8 | this.key = key;
9 | this.user = user;
10 | this.visitedKeys = visitedKeys;
11 | this.settings = settings;
12 | }
13 |
14 | private String key;
15 | private User user;
16 | private final List visitedKeys;
17 |
18 | private final Map settings;
19 | private boolean isUserMissing = false;
20 | private boolean isUserAttributeMissing = false;
21 |
22 | public String getKey() {
23 | return key;
24 | }
25 |
26 | public void setKey(String key) {
27 | this.key = key;
28 | }
29 |
30 | public User getUser() {
31 | return user;
32 | }
33 |
34 | public void setUser(User user) {
35 | this.user = user;
36 | }
37 |
38 | public boolean isUserMissing() {
39 | return isUserMissing;
40 | }
41 |
42 | public void setUserMissing(boolean userMissing) {
43 | isUserMissing = userMissing;
44 | }
45 |
46 | public boolean isUserAttributeMissing() {
47 | return isUserAttributeMissing;
48 | }
49 |
50 | public void setUserAttributeMissing(boolean userAttributeMissing) {
51 | isUserAttributeMissing = userAttributeMissing;
52 | }
53 |
54 | public List getVisitedKeys() {
55 | return visitedKeys;
56 | }
57 |
58 | public Map getSettings() {
59 | return settings;
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/TargetingRule.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | /**
6 | * Describes a targeting rule.
7 | */
8 | public class TargetingRule {
9 |
10 | @SerializedName(value = "c")
11 | private Condition[] conditions;
12 | @SerializedName(value = "p")
13 | private PercentageOption[] percentageOptions;
14 | @SerializedName(value = "s")
15 | private SimpleValue simpleValue;
16 |
17 | /**
18 | * The list of conditions that are combined with the AND logical operator.
19 | * Items can be one of the following types: {@link UserCondition}, {@link SegmentCondition} or {@link PrerequisiteFlagCondition}.
20 | */
21 | public Condition[] getConditions() {
22 | return conditions != null ? conditions : new Condition[]{};
23 | }
24 |
25 | /**
26 | * The list of percentage options associated with the targeting rule or {@code null} if the targeting rule has a simple value THEN part.
27 | */
28 | public PercentageOption[] getPercentageOptions() {
29 | return percentageOptions;
30 | }
31 |
32 | /**
33 | * The simple value associated with the targeting rule or {@code null} if the targeting rule has percentage options THEN part.
34 | */
35 | public SimpleValue getSimpleValue() {
36 | return simpleValue;
37 | }
38 | }
39 |
40 | class SimpleValue {
41 | @SerializedName(value = "v")
42 | private SettingValue value;
43 | @SerializedName(value = "i")
44 | private String variationId;
45 |
46 | public SettingValue getValue() {
47 | return value;
48 | }
49 |
50 | public String getVariationId() {
51 | return variationId;
52 | }
53 | }
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/options_within_targeting_rule.json:
--------------------------------------------------------------------------------
1 | {
2 | "sdkKey": "configcat-sdk-1/JcPbCGl_1E-K9M-fJOyKyQ/P4e3fAz_1ky2-Zg2e4cbkw",
3 | "tests": [
4 | {
5 | "key": "stringContainsString75Cat0Dog25Falcon0HorseDefaultCat",
6 | "defaultValue": "default",
7 | "returnValue": "Cat",
8 | "expectedLog": "options_within_targeting_rule_no_user.txt"
9 | },
10 | {
11 | "key": "stringContainsString75Cat0Dog25Falcon0HorseDefaultCat",
12 | "defaultValue": "default",
13 | "user": {
14 | "Identifier": "12345"
15 | },
16 | "returnValue": "Cat",
17 | "expectedLog": "options_within_targeting_rule_no_targeted_attribute.txt"
18 | },
19 | {
20 | "key": "stringContainsString75Cat0Dog25Falcon0HorseDefaultCat",
21 | "defaultValue": "default",
22 | "user": {
23 | "Identifier": "12345",
24 | "Email": "joe@example.com"
25 | },
26 | "returnValue": "Cat",
27 | "expectedLog": "options_within_targeting_rule_not_matching_targeted_attribute.txt"
28 | },
29 | {
30 | "key": "stringContainsString75Cat0Dog25Falcon0HorseDefaultCat",
31 | "defaultValue": "default",
32 | "user": {
33 | "Identifier": "12345",
34 | "Email": "joe@configcat.com"
35 | },
36 | "returnValue": "Cat",
37 | "expectedLog": "options_within_targeting_rule_matching_targeted_attribute_no_options_attribute.txt"
38 | },
39 | {
40 | "key": "stringContainsString75Cat0Dog25Falcon0HorseDefaultCat",
41 | "defaultValue": "default",
42 | "user": {
43 | "Identifier": "12345",
44 | "Email": "joe@configcat.com",
45 | "Country": "US"
46 | },
47 | "returnValue": "Cat",
48 | "expectedLog": "options_within_targeting_rule_matching_targeted_attribute_options_attribute.txt"
49 | }
50 | ]
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/LocalMapDataSource.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | class LocalMapDataSource extends OverrideDataSource {
7 | private final Map loadedSettings = new HashMap<>();
8 |
9 | public LocalMapDataSource(Map source) {
10 | if (source == null)
11 | throw new IllegalArgumentException("'source' cannot be null.");
12 |
13 | for (Map.Entry entry : source.entrySet()) {
14 | Setting setting = convertToSetting(entry.getValue());
15 | this.loadedSettings.put(entry.getKey(), setting);
16 | }
17 | }
18 |
19 | @Override
20 | public Map getLocalConfiguration() {
21 | return this.loadedSettings;
22 | }
23 |
24 | private Setting convertToSetting(Object object) {
25 | Setting setting = new Setting();
26 | SettingValue settingValue = new SettingValue();
27 | if (object instanceof String) {
28 | setting.setType(SettingType.STRING);
29 | settingValue.setStringValue((String) object);
30 | } else if (object instanceof Boolean) {
31 | setting.setType(SettingType.BOOLEAN);
32 | settingValue.setBooleanValue((Boolean) object);
33 | } else if (object instanceof Integer) {
34 | setting.setType(SettingType.INT);
35 | settingValue.setIntegerValue((Integer) object);
36 | } else if (object instanceof Double) {
37 | setting.setType(SettingType.DOUBLE);
38 | settingValue.setDoubleValue((Double) object);
39 | } else {
40 | throw new IllegalArgumentException("Only String, Integer, Double or Boolean types are supported.");
41 | }
42 | setting.setSettingsValue(settingValue);
43 | return setting;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/samples/android-java/app/src/main/java/com/configcat/configcatsample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.configcat.configcatsample;
2 |
3 | import android.os.Bundle;
4 | import android.util.Log;
5 | import android.widget.TextView;
6 |
7 | import androidx.appcompat.app.AppCompatActivity;
8 |
9 | import com.configcat.ConfigCatClient;
10 | import com.configcat.LogLevel;
11 | import com.configcat.SharedPreferencesCache;
12 | import com.configcat.User;
13 |
14 |
15 | public class MainActivity extends AppCompatActivity {
16 |
17 | private ConfigCatClient client;
18 |
19 | @Override
20 | protected void onCreate(Bundle savedInstanceState) {
21 | super.onCreate(savedInstanceState);
22 | setContentView(R.layout.activity_main);
23 |
24 | client = ConfigCatClient.get("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ", options -> {
25 | // Use ConfigCat's shared preferences cache.
26 | options.cache(new SharedPreferencesCache(getApplicationContext()));
27 |
28 | // Info level logging helps to inspect the feature flag evaluation process.
29 | // Use the default Warning level to avoid too detailed logging in your application.
30 | options.logLevel(LogLevel.DEBUG);
31 |
32 | options.hooks().addOnConfigChanged(map -> fetchNewConfig());
33 | });
34 | }
35 |
36 | private void fetchNewConfig() {
37 | User user = User.newBuilder()
38 | .email("someone@example.com")
39 | .build("key");
40 |
41 | this.client.getValueAsync(Boolean.class, "isPOCFeatureEnabled", user, false)
42 | .thenAccept(value -> {
43 | this.runOnUiThread(() -> {
44 | TextView viewById = this.findViewById(R.id.editText);
45 | viewById.setText("isPOCFeatureEnabled: " + value);
46 | });
47 | });
48 | }
49 |
50 | }
--------------------------------------------------------------------------------
/src/test/resources/evaluation/prerequisite_flag/prerequisite_flag.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'dependentFeature' for User '{"Identifier":"12345","Email":"kate@configcat.com","Country":"USA"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF Flag 'mainFeature' EQUALS 'target'
4 | (
5 | Evaluating prerequisite flag 'mainFeature':
6 | Evaluating targeting rules and applying the first match if any:
7 | - IF User.Email ENDS WITH ANY OF [<1 hashed value>] => false, skipping the remaining AND conditions
8 | THEN 'private' => no match
9 | - IF User.Country IS ONE OF [<1 hashed value>] => true
10 | AND User IS NOT IN SEGMENT 'Beta Users'
11 | (
12 | Evaluating segment 'Beta Users':
13 | - IF User.Email IS ONE OF [<2 hashed values>] => false, skipping the remaining AND conditions
14 | Segment evaluation result: User IS NOT IN SEGMENT.
15 | Condition (User IS NOT IN SEGMENT 'Beta Users') evaluates to true.
16 | ) => true
17 | AND User IS NOT IN SEGMENT 'Developers'
18 | (
19 | Evaluating segment 'Developers':
20 | - IF User.Email IS ONE OF [<2 hashed values>] => false, skipping the remaining AND conditions
21 | Segment evaluation result: User IS NOT IN SEGMENT.
22 | Condition (User IS NOT IN SEGMENT 'Developers') evaluates to true.
23 | ) => true
24 | THEN 'target' => MATCH, applying rule
25 | Prerequisite flag evaluation result: 'target'.
26 | Condition (Flag 'mainFeature' EQUALS 'target') evaluates to true.
27 | )
28 | THEN % options => MATCH, applying rule
29 | Evaluating % options based on the User.Identifier attribute:
30 | - Computing hash in the [0..99] range from User.Identifier => 78 (this value is sticky and consistent across all SDKs)
31 | - Hash value 78 selects % option 4 (25%), 'Horse'.
32 | Returning 'Horse'.
33 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/java/com/configcat/configcatsample/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.configcat.configcatsample
2 |
3 | import android.annotation.SuppressLint
4 | import androidx.appcompat.app.AppCompatActivity
5 | import android.os.Bundle
6 | import android.widget.TextView
7 | import com.configcat.*
8 |
9 | class MainActivity : AppCompatActivity() {
10 | private lateinit var client: ConfigCatClient
11 |
12 | @SuppressLint("SetTextI18n")
13 | override fun onCreate(savedInstanceState: Bundle?) {
14 | super.onCreate(savedInstanceState)
15 | setContentView(R.layout.activity_main)
16 |
17 | this.client = ConfigCatClient.get("PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ") { options ->
18 | options.pollingMode(PollingModes.autoPoll(5))
19 |
20 | // Use ConfigCat's shared preferences cache.
21 | options.cache(SharedPreferencesCache(this@MainActivity))
22 |
23 | // Info level logging helps to inspect the feature flag evaluation process.
24 | // Use the default Warning level to avoid too detailed logging in your application.
25 | options.logLevel(LogLevel.DEBUG)
26 |
27 | options.hooks().addOnConfigChanged {
28 | run {
29 | this.fetchNewConfig()
30 | }
31 | }
32 | }
33 | }
34 |
35 | @SuppressLint("SetTextI18n")
36 | fun fetchNewConfig() {
37 | val user = User.newBuilder()
38 | .email("someone@example.com")
39 | .build("key")
40 |
41 | this.client.getValueAsync(Boolean::class.java, "isPOCFeatureEnabled", user, false)
42 | .thenAccept { value ->
43 | this@MainActivity.runOnUiThread {
44 | val textField = findViewById(R.id.editText)
45 | textField.text = "isPOCFeatureEnabled: $value"
46 | }
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/samples/android-kotlin/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | sonarqube = "5.0.0.4638"
3 | maven-publish = "0.32.0"
4 | okhttp = "4.12.0"
5 | okio = "3.4.0" # indirect dependency to solve security vulnerability in 3.2.0
6 | slf4j-api = "1.7.36"
7 | gson = "2.9.0"
8 | commons-codec = "1.15"
9 | semantic-version = "2.1.1"
10 | junit-jupiter = "5.10.0"
11 | logback = "1.5.13"
12 | mockwebserver = "4.12.0"
13 | mockito = "4.8.0"
14 | android-retrofuture = "1.7.4"
15 | android-gradle = "8.0.0"
16 |
17 | [libraries]
18 | okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }
19 | okio = { module = "com.squareup.okio:okio", version.ref = "okio" }
20 | slf4j-api = { module = "org.slf4j:slf4j-api", version.ref = "slf4j-api" }
21 | gson = { module = "com.google.code.gson:gson", version.ref = "gson" }
22 | commons-codec = { module = "commons-codec:commons-codec", version.ref = "commons-codec" }
23 | semantic-version = { module = "de.skuzzle:semantic-version", version.ref = "semantic-version" }
24 | junit-jupiter-api = { module = "org.junit.jupiter:junit-jupiter-api", version.ref = "junit-jupiter" }
25 | logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" }
26 | logback-core = { module = "ch.qos.logback:logback-core", version.ref = "logback" }
27 | mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version.ref = "mockwebserver" }
28 | mockito-core = { module = "org.mockito:mockito-core", version.ref = "mockito" }
29 | junit-jupiter-params = { module = "org.junit.jupiter:junit-jupiter-params", version.ref = "junit-jupiter" }
30 | junit-jupiter-engine = { module = "org.junit.jupiter:junit-jupiter-engine", version.ref = "junit-jupiter" }
31 | android-retrofuture = { module = "net.sourceforge.streamsupport:android-retrofuture", version.ref = "android-retrofuture" }
32 | android-gradle = { module = "com.android.tools.build:gradle", version.ref = "android-gradle" }
33 |
34 |
35 | [plugins]
36 | sonarqube = { id = "org.sonarqube", version.ref = "sonarqube" }
37 | maven-publish = { id = "com.vanniktech.maven.publish", version.ref = "maven-publish" }
38 |
39 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/list_truncation/test_list_truncation.json:
--------------------------------------------------------------------------------
1 | {
2 | "p": {
3 | "u": "https://cdn-global.configcat.com",
4 | "r": 0,
5 | "s": "test-salt"
6 | },
7 | "f": {
8 | "booleanKey1": {
9 | "t": 0,
10 | "v": {
11 | "b": false
12 | },
13 | "r": [
14 | {
15 | "c": [
16 | {
17 | "u": {
18 | "a": "Identifier",
19 | "c": 2,
20 | "l": [
21 | "1",
22 | "2",
23 | "3",
24 | "4",
25 | "5",
26 | "6",
27 | "7",
28 | "8",
29 | "9",
30 | "10"
31 | ]
32 | }
33 | },
34 | {
35 | "u": {
36 | "a": "Identifier",
37 | "c": 2,
38 | "l": [
39 | "1",
40 | "2",
41 | "3",
42 | "4",
43 | "5",
44 | "6",
45 | "7",
46 | "8",
47 | "9",
48 | "10",
49 | "11"
50 | ]
51 | }
52 | },
53 | {
54 | "u": {
55 | "a": "Identifier",
56 | "c": 2,
57 | "l": [
58 | "1",
59 | "2",
60 | "3",
61 | "4",
62 | "5",
63 | "6",
64 | "7",
65 | "8",
66 | "9",
67 | "10",
68 | "11",
69 | "12"
70 | ]
71 | }
72 | }
73 | ],
74 | "s": {
75 | "v": {
76 | "b": true
77 | },
78 | "i": "test-variation-id"
79 | }
80 | }
81 | ],
82 | "i": "test-variation-id"
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/.github/workflows/scheduled-test.yml:
--------------------------------------------------------------------------------
1 | name: Android SDK Scheduled Test
2 |
3 | on:
4 | schedule:
5 | - cron: '0 8 * * 1'
6 |
7 | workflow_dispatch:
8 |
9 | jobs:
10 | test:
11 | runs-on: ubuntu-latest
12 | strategy:
13 | matrix:
14 | java-versions: [ 17 ]
15 | steps:
16 | - uses: actions/checkout@v6
17 |
18 | - name: Set up JDK
19 | uses: actions/setup-java@v5
20 | with:
21 | java-version: ${{ matrix.java-versions }}
22 | distribution: zulu
23 |
24 | - name: Cache Gradle packages
25 | uses: actions/cache@v5
26 | with:
27 | path: ~/.gradle/caches
28 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
29 | restore-keys: ${{ runner.os }}-gradle
30 |
31 | - name: Grant execute permission for gradlew
32 | run: chmod +x gradlew
33 |
34 | - name: Test with Gradle
35 | run: ./gradlew test
36 |
37 | coverage-scan:
38 | runs-on: ubuntu-latest
39 | steps:
40 | - uses: actions/checkout@v6
41 | with:
42 | fetch-depth: 0
43 |
44 | - name: Set up JDK
45 | uses: actions/setup-java@v5
46 | with:
47 | java-version: 17
48 | distribution: zulu
49 |
50 | - name: Cache SonarCloud packages
51 | uses: actions/cache@v5
52 | with:
53 | path: ~/.sonar/cache
54 | key: ${{ runner.os }}-sonar
55 | restore-keys: ${{ runner.os }}-sonar
56 |
57 | - name: Cache Gradle packages
58 | uses: actions/cache@v5
59 | with:
60 | path: ~/.gradle/caches
61 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
62 | restore-keys: ${{ runner.os }}-gradle
63 |
64 | - name: Grant execute permission for gradlew
65 | run: chmod +x gradlew
66 |
67 | - name: Check with Gradle
68 | run: ./gradlew check
69 |
70 | - name: Execute sonar scan
71 | run: ./gradlew sonar -Dbuild.number=$GITHUB_RUN_NUMBER
72 | env:
73 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
74 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
--------------------------------------------------------------------------------
/src/test/java/com/configcat/FormattableLogMessageTests.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import java.util.ArrayList;
6 | import java.util.HashSet;
7 | import java.util.List;
8 | import java.util.Set;
9 |
10 | import static org.junit.jupiter.api.Assertions.*;
11 |
12 | class FormattableLogMessageTests {
13 |
14 | @Test
15 | void hashCodeTest() {
16 | FormattableLogMessage obj1 = new FormattableLogMessage("message %s", "formatted");
17 | FormattableLogMessage obj2 = new FormattableLogMessage("message %s", "formatted");
18 |
19 | //test hashcode consistency
20 | assertEquals(obj1.hashCode(), obj1.hashCode());
21 |
22 | //test hashcode equality
23 | assertEquals(obj1.hashCode(), obj2.hashCode());
24 |
25 | //test hashcode distribution
26 | List objects = new ArrayList<>();
27 | for (int i = 0; i < 1000; i++) {
28 | objects.add(new FormattableLogMessage("message %s %d", "formatted", i));
29 | }
30 | Set hashCodes = new HashSet<>();
31 | for (FormattableLogMessage obj : objects) {
32 | hashCodes.add(obj.hashCode());
33 | }
34 | assertEquals(objects.size(), hashCodes.size());
35 | }
36 |
37 | @Test
38 | void equalsTest() {
39 | FormattableLogMessage obj1 = new FormattableLogMessage("message %s", "formatted");
40 | FormattableLogMessage obj2 = new FormattableLogMessage("message %s", "formatted");
41 |
42 | // assert equals
43 | boolean equalsResult = obj1.equals(obj2);
44 | assertTrue(equalsResult);
45 |
46 | // assert equals reverse
47 | equalsResult = obj2.equals(obj1);
48 | assertTrue(equalsResult);
49 |
50 | //assert not equals
51 | FormattableLogMessage obj3 = new FormattableLogMessage("message %s", "different");
52 | equalsResult = obj1.equals(obj3);
53 | assertFalse(equalsResult);
54 |
55 | //assert null
56 | equalsResult = obj1.equals(null);
57 | assertFalse(equalsResult);
58 | }
59 |
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Android SDK test
2 |
3 | on:
4 | push:
5 | branches-ignore:
6 | - master
7 | pull_request:
8 | branches: [ master ]
9 |
10 | workflow_dispatch:
11 |
12 | jobs:
13 | test:
14 | runs-on: ubuntu-latest
15 | strategy:
16 | matrix:
17 | java-versions: [ 17 ]
18 | steps:
19 | - uses: actions/checkout@v6
20 |
21 | - name: Set up JDK
22 | uses: actions/setup-java@v5
23 | with:
24 | java-version: ${{ matrix.java-versions }}
25 | distribution: zulu
26 |
27 | - name: Cache Gradle packages
28 | uses: actions/cache@v5
29 | with:
30 | path: ~/.gradle/caches
31 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
32 | restore-keys: ${{ runner.os }}-gradle
33 |
34 | - name: Grant execute permission for gradlew
35 | run: chmod +x gradlew
36 |
37 | - name: Test with Gradle
38 | run: ./gradlew test
39 |
40 | coverage-scan:
41 | runs-on: ubuntu-latest
42 | steps:
43 | - uses: actions/checkout@v6
44 | with:
45 | fetch-depth: 0
46 |
47 | - name: Set up JDK
48 | uses: actions/setup-java@v5
49 | with:
50 | java-version: 17
51 | distribution: zulu
52 |
53 | - name: Cache SonarCloud packages
54 | uses: actions/cache@v5
55 | with:
56 | path: ~/.sonar/cache
57 | key: ${{ runner.os }}-sonar
58 | restore-keys: ${{ runner.os }}-sonar
59 |
60 | - name: Cache Gradle packages
61 | uses: actions/cache@v5
62 | with:
63 | path: ~/.gradle/caches
64 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
65 | restore-keys: ${{ runner.os }}-gradle
66 |
67 | - name: Grant execute permission for gradlew
68 | run: chmod +x gradlew
69 |
70 | - name: Check with Gradle
71 | run: ./gradlew check
72 |
73 | - name: Execute sonar scan
74 | run: ./gradlew sonar -Dbuild.number=$GITHUB_RUN_NUMBER
75 | env:
76 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
77 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
78 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/UserCondition.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | /**
6 | * Describes a condition that is based on a User Object attribute.
7 | */
8 | public class UserCondition implements ConditionAccessor {
9 |
10 | @SerializedName(value = "a")
11 | private String comparisonAttribute;
12 | @SerializedName(value = "c")
13 | private int comparator;
14 | @SerializedName("s")
15 | private String stringValue;
16 | @SerializedName("d")
17 | private Double doubleValue;
18 | @SerializedName("l")
19 | private String[] stringArrayValue;
20 |
21 | /**
22 | * The User Object attribute that the condition is based on. Can be "Identifier", "Email", "Country" or any custom attribute.
23 | */
24 | public String getComparisonAttribute() {
25 | return comparisonAttribute;
26 | }
27 |
28 | /**
29 | * The operator which defines the relation between the comparison attribute and the comparison value.
30 | */
31 | public int getComparator() {
32 | return comparator;
33 | }
34 |
35 | /**
36 | * The String value that the User Object attribute is compared or {@code null} if the comparator use a different type of value.
37 | */
38 | public String getStringValue() {
39 | return stringValue;
40 | }
41 |
42 | /**
43 | * The Double value that the User Object attribute is compared or {@code null} if the comparator use a different type of value.
44 | */
45 | public Double getDoubleValue() {
46 | return doubleValue;
47 | }
48 |
49 | /**
50 | * The String Array value that the User Object attribute is compared or {@code null} if the comparator use a different type of value.
51 | */
52 | public String[] getStringArrayValue() {
53 | return stringArrayValue;
54 | }
55 |
56 | @Override
57 | public UserCondition getUserCondition() {
58 | return this;
59 | }
60 |
61 | @Override
62 | public SegmentCondition getSegmentCondition() {
63 | return null;
64 | }
65 |
66 | @Override
67 | public PrerequisiteFlagCondition getPrerequisiteFlagCondition() {
68 | return null;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to the ConfigCat SDK for Android
2 |
3 | ConfigCat SDK is an open source project. Feedback and contribution are welcome. Contributions are made to this repo via Issues and Pull Requests.
4 |
5 | ## Submitting bug reports and feature requests
6 |
7 | The ConfigCat SDK team monitors the [issue tracker](https://github.com/configcat/android-sdk/issues) in the SDK repository. Bug reports and feature requests specific to this SDK should be filed in this issue tracker. The team will respond to all newly filed issues.
8 |
9 | ## Submitting pull requests
10 |
11 | We encourage pull requests and other contributions from the community.
12 | - Before submitting pull requests, ensure that all temporary or unintended code is removed.
13 | - Be accompanied by a complete Pull Request template (loaded automatically when a PR is created).
14 | - Add unit or integration tests for fixed or changed functionality.
15 |
16 | When you submit a pull request or otherwise seek to include your change in the repository, you waive all your intellectual property rights, including your copyright and patent claims for the submission. For more details please read the [contribution agreement](https://github.com/configcat/legal/blob/main/contribution-agreement.md).
17 |
18 | In general, we follow the ["fork-and-pull" Git workflow](https://github.com/susam/gitpr)
19 |
20 | 1. Fork the repository to your own Github account
21 | 2. Clone the project to your machine
22 | 3. Create a branch locally with a succinct but descriptive name
23 | 4. Commit changes to the branch
24 | 5. Following any formatting and testing guidelines specific to this repo
25 | 6. Push changes to your fork
26 | 7. Open a PR in our repository and follow the PR template so that we can efficiently review the changes.
27 |
28 | ## Building and running tests
29 |
30 | ### From command line with Gradle
31 |
32 | - On Windows:
33 |
34 | ```bash
35 | gradlew test
36 | ```
37 |
38 | - On Mac or Linux:
39 |
40 | ```bash
41 | ./gradlew test
42 | ```
43 |
44 | ### From Android Studio
45 |
46 | 1. Open the `android-sdk` project in [Android Studio](https://developer.android.com/studio/index.html)
47 | 2. Open the context menu of android-sdk [configcat-android-client] project
48 | 3. Select Run 'Tests in 'configcat-...'
49 |
--------------------------------------------------------------------------------
/src/test/resources/matrix/testmatrix_unicode.csv:
--------------------------------------------------------------------------------
1 | Identifier;Email;Country;🆃🅴🆇🆃;boolTextEqualsHashed;boolTextEqualsCleartext;boolTextNotEqualsHashed;boolTextNotEqualsCleartext;boolIsOneOfHashed;boolIsOneOfCleartext;boolIsNotOneOfHashed;boolIsNotOneOfCleartext;boolStartsWithHashed;boolStartsWithCleartext;boolNotStartsWithHashed;boolNotStartsWithCleartext;boolEndsWithHashed;boolEndsWithCleartext;boolNotEndsWithHashed;boolNotEndsWithCleartext;boolContainsCleartext;boolNotContainsCleartext;boolArrayContainsHashed;boolArrayContainsCleartext;boolArrayNotContainsHashed;boolArrayNotContainsCleartext
2 | 1;;;ʄǟռƈʏ ȶɛӼȶ;True;True;False;False;False;False;True;True;False;False;True;True;False;False;True;True;False;True;False;False;False;False
3 | 1;;;ʄaռƈʏ ȶɛӼȶ;False;False;True;True;False;False;True;True;False;False;True;True;False;False;True;True;False;True;False;False;False;False
4 | 1;;;ÁRVÍZTŰRŐ tükörfúrógép;False;False;True;True;True;True;False;False;True;True;False;False;True;True;False;False;True;False;False;False;False;False
5 | 1;;;árvíztűrő tükörfúrógép;False;False;True;True;False;False;True;True;False;False;True;True;True;True;False;False;True;False;False;False;False;False
6 | 1;;;ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP;False;False;True;True;False;False;True;True;True;True;False;False;False;False;True;True;True;False;False;False;False;False
7 | 1;;;árvíztűrő TÜKÖRFÚRÓGÉP;False;False;True;True;False;False;True;True;False;False;True;True;False;False;True;True;False;True;False;False;False;False
8 | 1;;;u𝖓𝖎𝖈𝖔𝖉e;False;False;True;True;True;True;False;False;True;True;False;False;True;True;False;False;True;False;False;False;False;False
9 | ;;;𝖚𝖓𝖎𝖈𝖔𝖉e;False;False;True;True;False;False;True;True;False;False;True;True;True;True;False;False;True;False;False;False;False;False
10 | ;;;u𝖓𝖎𝖈𝖔𝖉𝖊;False;False;True;True;False;False;True;True;True;True;False;False;False;False;True;True;True;False;False;False;False;False
11 | ;;;𝖚𝖓𝖎𝖈𝖔𝖉𝖊;False;False;True;True;False;False;True;True;False;False;True;True;False;False;True;True;False;True;False;False;False;False
12 | 1;;;["ÁRVÍZTŰRŐ tükörfúrógép", "unicode"];False;False;True;True;False;False;True;True;False;False;True;True;False;False;True;True;True;False;True;True;False;False
13 | 1;;;["ÁRVÍZTŰRŐ", "tükörfúrógép", "u𝖓𝖎𝖈𝖔𝖉e"];False;False;True;True;False;False;True;True;False;False;True;True;False;False;True;True;True;False;True;True;False;False
14 | 1;;;["ÁRVÍZTŰRŐ", "tükörfúrógép", "unicode"];False;False;True;True;False;False;True;True;False;False;True;True;False;False;True;True;True;False;False;False;True;True
15 |
--------------------------------------------------------------------------------
/src/test/resources/test_circulardependency.json:
--------------------------------------------------------------------------------
1 | {
2 | "p": {
3 | "u": "https://cdn-global.configcat.com",
4 | "r": 0,
5 | "s": "test-salt"
6 | },
7 | "f": {
8 | "key1": {
9 | "t": 1,
10 | "v": {
11 | "s": "key1-value"
12 | },
13 | "r": [
14 | {
15 | "c": [
16 | {
17 | "p": {
18 | "f": "key1",
19 | "c": 0,
20 | "v": {
21 | "s": "key1-prereq"
22 | }
23 | }
24 | }
25 | ],
26 | "s": {
27 | "v": {
28 | "s": "key1-prereq"
29 | }
30 | }
31 | }
32 | ]
33 | },
34 | "key2": {
35 | "t": 1,
36 | "v": {
37 | "s": "key2-value"
38 | },
39 | "r": [
40 | {
41 | "c": [
42 | {
43 | "p": {
44 | "f": "key3",
45 | "c": 0,
46 | "v": {
47 | "s": "key3-prereq"
48 | }
49 | }
50 | }
51 | ],
52 | "s": {
53 | "v": {
54 | "s": "key2-prereq"
55 | }
56 | }
57 | }
58 | ]
59 | },
60 | "key3": {
61 | "t": 1,
62 | "v": {
63 | "s": "key3-value"
64 | },
65 | "r": [
66 | {
67 | "c": [
68 | {
69 | "p": {
70 | "f": "key2",
71 | "c": 0,
72 | "v": {
73 | "s": "key2-prereq"
74 | }
75 | }
76 | }
77 | ],
78 | "s": {
79 | "v": {
80 | "s": "key3-prereq"
81 | }
82 | }
83 | }
84 | ]
85 | },
86 | "key4": {
87 | "t": 1,
88 | "v": {
89 | "s": "key4-value"
90 | },
91 | "r": [
92 | {
93 | "c": [
94 | {
95 | "p": {
96 | "f": "key3",
97 | "c": 0,
98 | "v": {
99 | "s": "key3-prereq"
100 | }
101 | }
102 | }
103 | ],
104 | "s": {
105 | "v": {
106 | "s": "key4-prereq"
107 | }
108 | }
109 | }
110 | ]
111 | }
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/Setting.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | /**
6 | * Feature flag or setting.
7 | */
8 | public class Setting {
9 |
10 | @SerializedName(value = "t")
11 | private SettingType type = SettingType.BOOLEAN;
12 | @SerializedName(value = "a")
13 | private String percentageAttribute;
14 | @SerializedName(value = "p")
15 | private PercentageOption[] percentageOptions;
16 | @SerializedName(value = "r")
17 | private TargetingRule[] targetingRules;
18 | @SerializedName(value = "v")
19 | private SettingValue settingValue;
20 | @SerializedName(value = "i")
21 | private String variationId;
22 |
23 | private String configSalt;
24 | private Segment[] segments;
25 |
26 | public void setSettingsValue(SettingValue settingValue) {
27 | this.settingValue = settingValue;
28 | }
29 |
30 | public void setType(SettingType type) {
31 | this.type = type;
32 | }
33 |
34 | public void setConfigSalt(String configSalt) {
35 | this.configSalt = configSalt;
36 | }
37 |
38 | public void setSegments(Segment[] segments) {
39 | this.segments = segments;
40 | }
41 |
42 | /**
43 | * Setting type.
44 | */
45 | public SettingType getType() {
46 | return type;
47 | }
48 |
49 | /**
50 | * The User Object attribute which serves as the basis of percentage options evaluation.
51 | */
52 | public String getPercentageAttribute() {
53 | return percentageAttribute;
54 | }
55 |
56 | /**
57 | * The list of percentage options.
58 | */
59 | public PercentageOption[] getPercentageOptions() {
60 | return percentageOptions;
61 | }
62 |
63 | /**
64 | * The list of targeting rules (where there is a logical OR relation between the items).
65 | */
66 | public TargetingRule[] getTargetingRules() {
67 | return targetingRules;
68 | }
69 |
70 | /**
71 | * Setting value.
72 | * Can be a value of the following types: {@link Boolean}, {@link String}, {@link Integer} or {@link Double}.
73 | */
74 | public SettingValue getSettingsValue() {
75 | return settingValue;
76 | }
77 |
78 | /**
79 | * Variation ID.
80 | */
81 | public String getVariationId() {
82 | return variationId;
83 | }
84 |
85 | public String getConfigSalt() {
86 | return configSalt;
87 | }
88 |
89 | public Segment[] getSegments() {
90 | return segments;
91 | }
92 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/SettingValue.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.annotations.SerializedName;
4 |
5 | import java.util.Objects;
6 |
7 | /**
8 | * Describes the setting type-specific value of a setting or feature flag.
9 | */
10 | public class SettingValue {
11 | @SerializedName("b")
12 | private Boolean booleanValue;
13 |
14 | @SerializedName("s")
15 | private String stringValue;
16 |
17 | @SerializedName("i")
18 | private Integer integerValue;
19 |
20 | @SerializedName("d")
21 | private Double doubleValue;
22 |
23 | public void setBooleanValue(Boolean booleanValue) {
24 | this.booleanValue = booleanValue;
25 | }
26 |
27 | public void setStringValue(String stringValue) {
28 | this.stringValue = stringValue;
29 | }
30 |
31 | public void setIntegerValue(Integer integerValue) {
32 | this.integerValue = integerValue;
33 | }
34 |
35 | public void setDoubleValue(Double doubleValue) {
36 | this.doubleValue = doubleValue;
37 | }
38 |
39 | public Boolean getBooleanValue() {
40 | return booleanValue;
41 | }
42 |
43 | public String getStringValue() {
44 | return stringValue;
45 | }
46 |
47 | public Integer getIntegerValue() {
48 | return integerValue;
49 | }
50 |
51 | public Double getDoubleValue() {
52 | return doubleValue;
53 | }
54 |
55 | public boolean equalsBasedOnSettingType(Object o, SettingType settingType) {
56 | if (this == o) return true;
57 | if (o == null || getClass() != o.getClass()) return false;
58 | SettingValue that = (SettingValue) o;
59 | switch (settingType){
60 | case BOOLEAN:
61 | return Objects.equals(booleanValue, that.booleanValue);
62 | case STRING:
63 | return Objects.equals(stringValue, that.stringValue);
64 | case INT:
65 | return Objects.equals(integerValue, that.integerValue);
66 | case DOUBLE:
67 | return Objects.equals(doubleValue, that.doubleValue);
68 | default:
69 | throw new IllegalStateException("Setting is of an unsupported type (" + settingType.name() + ").");
70 | }
71 | }
72 |
73 | @Override
74 | public String toString() {
75 | if (booleanValue != null) {
76 | return booleanValue.toString();
77 | } else if (integerValue != null) {
78 | return integerValue.toString();
79 | } else if (doubleValue != null) {
80 | return doubleValue.toString();
81 | } else {
82 | return stringValue;
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/samples/android-kotlin/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/semver_validation/semver_relations_error.txt:
--------------------------------------------------------------------------------
1 | WARNING [3004] Cannot evaluate condition (User.Custom1 < '1.0.0,') for setting 'relations' ('wrong_semver' is not a valid semantic version). Please check the User.Custom1 attribute and make sure that its value corresponds to the comparison operator.
2 | WARNING [3004] Cannot evaluate condition (User.Custom1 < '1.0.0') for setting 'relations' ('wrong_semver' is not a valid semantic version). Please check the User.Custom1 attribute and make sure that its value corresponds to the comparison operator.
3 | WARNING [3004] Cannot evaluate condition (User.Custom1 <= '1.0.0') for setting 'relations' ('wrong_semver' is not a valid semantic version). Please check the User.Custom1 attribute and make sure that its value corresponds to the comparison operator.
4 | WARNING [3004] Cannot evaluate condition (User.Custom1 > '2.0.0') for setting 'relations' ('wrong_semver' is not a valid semantic version). Please check the User.Custom1 attribute and make sure that its value corresponds to the comparison operator.
5 | WARNING [3004] Cannot evaluate condition (User.Custom1 >= '2.0.0') for setting 'relations' ('wrong_semver' is not a valid semantic version). Please check the User.Custom1 attribute and make sure that its value corresponds to the comparison operator.
6 | INFO [5000] Evaluating 'relations' for User '{"Identifier":"12345","Custom1":"wrong_semver"}'
7 | Evaluating targeting rules and applying the first match if any:
8 | - IF User.Custom1 < '1.0.0,' THEN '<1.0.0,' => cannot evaluate, the User.Custom1 attribute is invalid ('wrong_semver' is not a valid semantic version)
9 | The current targeting rule is ignored and the evaluation continues with the next rule.
10 | - IF User.Custom1 < '1.0.0' THEN '< 1.0.0' => cannot evaluate, the User.Custom1 attribute is invalid ('wrong_semver' is not a valid semantic version)
11 | The current targeting rule is ignored and the evaluation continues with the next rule.
12 | - IF User.Custom1 <= '1.0.0' THEN '<=1.0.0' => cannot evaluate, the User.Custom1 attribute is invalid ('wrong_semver' is not a valid semantic version)
13 | The current targeting rule is ignored and the evaluation continues with the next rule.
14 | - IF User.Custom1 > '2.0.0' THEN '>2.0.0' => cannot evaluate, the User.Custom1 attribute is invalid ('wrong_semver' is not a valid semantic version)
15 | The current targeting rule is ignored and the evaluation continues with the next rule.
16 | - IF User.Custom1 >= '2.0.0' THEN '>=2.0.0' => cannot evaluate, the User.Custom1 attribute is invalid ('wrong_semver' is not a valid semantic version)
17 | The current targeting rule is ignored and the evaluation continues with the next rule.
18 | Returning 'Default'.
19 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/Entry.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | public class Entry {
4 | private final Config config;
5 | private final String eTag;
6 | private final String configJson;
7 | private final long fetchTime;
8 |
9 | public Config getConfig() {
10 | return config;
11 | }
12 |
13 | public String getETag() {
14 | return eTag;
15 | }
16 |
17 | public long getFetchTime() {
18 | return fetchTime;
19 | }
20 |
21 | public String getConfigJson() {
22 | return configJson;
23 | }
24 |
25 | public Entry withFetchTime(long fetchTime) {
26 | return new Entry(getConfig(), getETag(), getConfigJson(), fetchTime);
27 | }
28 |
29 | public Entry(Config config, String eTag, String configJson, long fetchTime) {
30 | this.config = config;
31 | this.eTag = eTag;
32 | this.configJson = configJson;
33 | this.fetchTime = fetchTime;
34 | }
35 |
36 | boolean isEmpty() {
37 | return EMPTY.equals(this);
38 | }
39 |
40 | public boolean isExpired(long threshold) {
41 | return fetchTime <= threshold ;
42 | }
43 |
44 | public static final Entry EMPTY = new Entry(Config.EMPTY, "", "", Constants.DISTANT_PAST);
45 |
46 | public String serialize() {
47 | return getFetchTime() + "\n" + getETag() + "\n" + getConfigJson();
48 | }
49 |
50 | public static Entry fromString(String cacheValue) throws IllegalArgumentException {
51 | if (cacheValue == null || cacheValue.isEmpty()) {
52 | return Entry.EMPTY;
53 | }
54 |
55 | int fetchTimeIndex = cacheValue.indexOf("\n");
56 | int eTagIndex = cacheValue.indexOf("\n", fetchTimeIndex + 1);
57 | if (fetchTimeIndex < 0 || eTagIndex < 0) {
58 | throw new IllegalArgumentException("Number of values is fewer than expected.");
59 | }
60 | String fetchTimeRaw = cacheValue.substring(0, fetchTimeIndex);
61 | if (!DateTimeUtils.isValidDate(fetchTimeRaw)) {
62 | throw new IllegalArgumentException("Invalid fetch time: " + fetchTimeRaw);
63 | }
64 | long fetchTimeUnixMillis = Long.parseLong(fetchTimeRaw);
65 | String eTag = cacheValue.substring(fetchTimeIndex + 1, eTagIndex);
66 | if (eTag.isEmpty()) {
67 | throw new IllegalArgumentException("Empty eTag value.");
68 | }
69 | String configJson = cacheValue.substring(eTagIndex + 1);
70 | if (configJson.isEmpty()) {
71 | throw new IllegalArgumentException("Empty config jsom value.");
72 | }
73 | try {
74 | Config config = Utils.deserializeConfig(configJson);
75 | return new Entry(config, eTag, configJson, fetchTimeUnixMillis);
76 | } catch (Exception e) {
77 | throw new IllegalArgumentException("Invalid config JSON content: " + configJson);
78 | }
79 | }
80 |
81 | }
--------------------------------------------------------------------------------
/src/test/java/com/configcat/Helpers.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import java.io.ByteArrayOutputStream;
4 | import java.io.IOException;
5 | import java.io.InputStream;
6 | import java.nio.charset.StandardCharsets;
7 | import java.util.function.Supplier;
8 |
9 | final class Helpers {
10 |
11 | public static final String SDK_KEY = "configcat-sdk-1/TEST_KEY-0123456789012/1234567890123456789012";
12 | public static final String RULES_JSON = "{ p: { s: 'test-salt' }, f: { key: { t: 1, v: {s: 'def'}, t: 1, i: 'defVar', p: [] , r: [ {c: [ {u: { a: 'Identifier', c: 2, l: ['@test1.com']}}],s: { v: {s: 'fake1'},i: 'id1'}},{c: [{u: {a: 'Identifier', c: 2,l: ['@test2.com']}}],s: { v: {s: 'fake2'},i: 'id2'}}] } } }";
13 |
14 |
15 | static String cacheValueFromConfigJson(String json) {
16 | Config config = Utils.gson.fromJson(json, Config.class);
17 | Entry entry = new Entry(config, "fakeTag", json, System.currentTimeMillis());
18 | return entry.serialize();
19 | }
20 |
21 | static String cacheValueFromConfigJsonAndTime(String json, long time) {
22 | Config config = Utils.gson.fromJson(json, Config.class);
23 | Entry entry = new Entry(config, "fakeTag", json, time);
24 | return entry.serialize();
25 | }
26 |
27 | static void waitFor(Supplier predicate) throws InterruptedException {
28 | waitFor(2000, predicate);
29 | }
30 |
31 | static void waitFor(long timeout, Supplier predicate) throws InterruptedException {
32 | long end = System.currentTimeMillis() + timeout;
33 | while (!predicate.get()) {
34 | Thread.sleep(200);
35 | if (System.currentTimeMillis() > end) {
36 | throw new RuntimeException("Test timed out.");
37 | }
38 | }
39 | }
40 |
41 | static void waitForClientCacheState(long timeout, Supplier predicate) throws InterruptedException {
42 | long end = System.currentTimeMillis() + timeout;
43 | while (predicate.get() == null) {
44 | Thread.sleep(200);
45 | if (System.currentTimeMillis() > end) {
46 | throw new RuntimeException("Test timed out.");
47 | }
48 | }
49 | }
50 |
51 | public static String readFileFromClassPath(String fileName) throws IOException {
52 | try (InputStream stream = Helpers.class.getClassLoader().getResourceAsStream(fileName)) {
53 | if (stream == null) {
54 | throw new IOException();
55 | }
56 | byte[] buffer = new byte[4096];
57 | ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
58 | int temp;
59 | while ((temp = stream.read(buffer)) != -1) {
60 | outputStream.write(buffer, 0, temp);
61 | }
62 | return new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/ConfigCatLogger.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import org.slf4j.Logger;
4 |
5 | class ConfigCatLogger {
6 | private final Logger logger;
7 | private final LogLevel logLevel;
8 | private final ConfigCatHooks hooks;
9 | private final LogFilterFunction filterFunction;
10 |
11 | public ConfigCatLogger(Logger logger, LogLevel logLevel, ConfigCatHooks hooks, LogFilterFunction filterFunction ) {
12 | this.logger = logger;
13 | this.logLevel = logLevel;
14 | this.hooks = hooks;
15 | this.filterFunction = filterFunction;
16 | }
17 |
18 | public ConfigCatLogger(Logger logger, LogLevel logLevel, ConfigCatHooks hooks) {
19 | this.logger = logger;
20 | this.logLevel = logLevel;
21 | this.hooks = hooks;
22 | this.filterFunction = null;
23 | }
24 |
25 | public ConfigCatLogger(Logger logger, LogLevel logLevel) {
26 | this.logger = logger;
27 | this.logLevel = logLevel;
28 | this.hooks = null;
29 | this.filterFunction = null;
30 | }
31 |
32 | public ConfigCatLogger(Logger logger) {
33 | this.logger = logger;
34 | this.logLevel = LogLevel.WARNING;
35 | this.hooks = null;
36 | this.filterFunction = null;
37 | }
38 |
39 | public void warn(int eventId, Object message) {
40 | if (filter(eventId, LogLevel.WARNING, message, null)) {
41 | this.logger.warn("[{}] {}", eventId, message);
42 | }
43 | }
44 |
45 | public void error(int eventId, Object message, Throwable exception) {
46 | if (this.hooks != null) this.hooks.invokeOnError(message);
47 | if (filter(eventId, LogLevel.ERROR, message, exception)) {
48 | String exceptionMessage = exception == null || exception.getMessage() == null ? "" : exception.getMessage();
49 | this.logger.error("[{}] {} {}", eventId, message, exceptionMessage, exception);
50 | }
51 | }
52 |
53 | public void error(int eventId, Object message) {
54 | if (this.hooks != null) this.hooks.invokeOnError(message);
55 | if (filter(eventId, LogLevel.ERROR, message, null)) {
56 | this.logger.error("[{}] {}", eventId, message);
57 | }
58 | }
59 |
60 | public void info(int eventId, Object message) {
61 | if (filter(eventId, LogLevel.INFO, message, null)) {
62 | this.logger.info("[{}] {}", eventId, message);
63 | }
64 | }
65 |
66 | public void debug(String message) {
67 | if (filter(0, LogLevel.DEBUG, message, null)) {
68 | this.logger.debug("[{}] {}", 0, message);
69 | }
70 | }
71 |
72 | private boolean filter(int eventId, LogLevel logLevel, Object message, Throwable exception) {
73 | return this.logLevel.ordinal() <= logLevel.ordinal() && (this.filterFunction == null || this.filterFunction.apply(logLevel, eventId, message, exception));
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/samples/android-java/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/Utils.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.GsonBuilder;
5 | import org.apache.commons.codec.binary.Hex;
6 | import org.apache.commons.codec.digest.DigestUtils;
7 |
8 | final class Utils {
9 | private Utils() { /* prevent from instantiation*/ }
10 |
11 | static final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
12 |
13 | public static Config deserializeConfig(String json) {
14 | if (json == null || json.isEmpty()) {
15 | throw new IllegalArgumentException("Config JSON content cannot be null or empty.");
16 | }
17 | Config config = Utils.gson.fromJson(json, Config.class);
18 |
19 | if (config == null) {
20 | throw new IllegalArgumentException("Invalid config JSON content: " + json);
21 | }
22 |
23 | String salt = config.getPreferences() != null ? config.getPreferences().getSalt() : null;
24 | Segment[] segments = config.getSegments();
25 | if (segments == null) {
26 | segments = new Segment[]{};
27 | }
28 | for (Setting setting : config.getEntries().values()) {
29 | setting.setConfigSalt(salt);
30 | setting.setSegments(segments);
31 | }
32 | return config;
33 | }
34 |
35 | public static String sha256(byte[] byteArray) {
36 | return new String(Hex.encodeHex(DigestUtils.sha256(byteArray)));
37 | }
38 |
39 | public static String sha256(String text) {
40 | return new String(Hex.encodeHex(DigestUtils.sha256(text)));
41 | }
42 |
43 | public static String sha1(String text) {
44 | return new String(Hex.encodeHex(DigestUtils.sha1(text)));
45 | }
46 |
47 | public static String sha1(byte[] byteArray) {
48 | return new String(Hex.encodeHex(DigestUtils.sha1(byteArray)));
49 | }
50 | }
51 |
52 | final class Constants {
53 | private Constants() { /* prevent from instantiation*/ }
54 |
55 | static final long DISTANT_FUTURE = Long.MAX_VALUE;
56 | static final long DISTANT_PAST = 0;
57 | static final String CONFIG_JSON_NAME = "config_v6.json";
58 | static final String SERIALIZATION_FORMAT_VERSION = "v2";
59 | static final String VERSION = "10.4.3";
60 |
61 | static final String SDK_KEY_PROXY_PREFIX = "configcat-proxy/";
62 | static final String SDK_KEY_PREFIX = "configcat-sdk-1";
63 |
64 | static final int SDK_KEY_SECTION_LENGTH = 22;
65 | }
66 |
67 | final class Result {
68 | private final T value;
69 | private final Object error;
70 |
71 | private Result(T value, Object error) {
72 | this.value = value;
73 | this.error = error;
74 | }
75 |
76 | T value() {
77 | return this.value;
78 | }
79 |
80 | Object error() {
81 | return this.error;
82 | }
83 |
84 | static Result error(Object error, T value) {
85 | return new Result<>(value, error);
86 | }
87 |
88 | static Result success(T value) {
89 | return new Result<>(value, null);
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/test/java/com/configcat/EvaluationLoggerTurnOffTest.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import ch.qos.logback.classic.Level;
4 | import ch.qos.logback.classic.Logger;
5 | import ch.qos.logback.classic.spi.ILoggingEvent;
6 | import ch.qos.logback.core.read.ListAppender;
7 | import org.junit.jupiter.api.Test;
8 | import org.slf4j.LoggerFactory;
9 |
10 | import java.io.IOException;
11 | import java.util.List;
12 |
13 | import static org.junit.jupiter.api.Assertions.assertEquals;
14 |
15 | // Test cases based on EvaluationTest 1_rule_no_user test case.
16 | class EvaluationLoggerTurnOffTest {
17 | @Test
18 | void testEvaluationLogLevelInfo() throws IOException {
19 |
20 | ConfigCatClient client = ConfigCatClient.get("PKDVCLf-Hq-h-kCzMp-L7Q/psuH7BGHoUmdONrzzUOY7A", options -> {
21 | options.pollingMode(PollingModes.manualPoll());
22 | options.logLevel(LogLevel.INFO);
23 | });
24 |
25 | client.forceRefresh();
26 |
27 | Logger clientLogger = (Logger) LoggerFactory.getLogger(ConfigCatClient.class);
28 | // create and start a ListAppender
29 | clientLogger.setLevel(Level.INFO);
30 | ListAppender listAppender = new ListAppender<>();
31 | listAppender.start();
32 |
33 | clientLogger.addAppender(listAppender);
34 |
35 | String returnValue = client.getValue(String.class, "stringContainsDogDefaultCat", null, "default");
36 |
37 | assertEquals("Cat", returnValue, "Return value not match.");
38 |
39 | List logsList = listAppender.list;
40 | assertEquals(2, logsList.size(), "Logged event size not match.");
41 | assertEquals(Level.WARN, logsList.get(0).getLevel(), "LogLevel mismatch.");
42 | assertEquals(Level.INFO, logsList.get(1).getLevel(), "LogLevel mismatch.");
43 |
44 | client.close();
45 | }
46 |
47 | @Test
48 | void testEvaluationLogLevelWarning() throws IOException {
49 | //based on 1_rule_no_user test case.
50 | ConfigCatClient client = ConfigCatClient.get("PKDVCLf-Hq-h-kCzMp-L7Q/psuH7BGHoUmdONrzzUOY7A", options -> {
51 | options.pollingMode(PollingModes.manualPoll());
52 | options.logLevel(LogLevel.WARNING);
53 | });
54 |
55 | client.forceRefresh();
56 |
57 | Logger clientLogger = (Logger) LoggerFactory.getLogger(ConfigCatClient.class);
58 | // create and start a ListAppender
59 | clientLogger.setLevel(Level.INFO);
60 | ListAppender listAppender = new ListAppender<>();
61 | listAppender.start();
62 |
63 | clientLogger.addAppender(listAppender);
64 |
65 | String returnValue = client.getValue(String.class, "stringContainsDogDefaultCat", null, "default");
66 |
67 | assertEquals("Cat", returnValue, "Return value not match.");
68 |
69 | List logsList = listAppender.list;
70 | assertEquals(1, logsList.size(), "Logged event size not match.");
71 | assertEquals(Level.WARN, logsList.get(0).getLevel(), "LogLevel mismatch.");
72 |
73 | client.close();
74 | }
75 |
76 | }
--------------------------------------------------------------------------------
/src/test/resources/evaluation/prerequisite_flag/prerequisite_flag_no_user_needed_by_both.txt:
--------------------------------------------------------------------------------
1 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'dependentFeatureWithUserCondition2' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
2 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'mainFeature' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
3 | WARNING [3001] Cannot evaluate targeting rules and % options for setting 'mainFeature' (User Object is missing). You should pass a User Object to the evaluation methods like `getValue()`/`getValueAsync()` in order to make targeting work properly. Read more: https://configcat.com/docs/advanced/user-object/
4 | INFO [5000] Evaluating 'dependentFeatureWithUserCondition2'
5 | Evaluating targeting rules and applying the first match if any:
6 | - IF User.Email IS ONE OF [<2 hashed values>] THEN 'Dog' => cannot evaluate, User Object is missing
7 | The current targeting rule is ignored and the evaluation continues with the next rule.
8 | - IF Flag 'mainFeature' EQUALS 'public'
9 | (
10 | Evaluating prerequisite flag 'mainFeature':
11 | Evaluating targeting rules and applying the first match if any:
12 | - IF User.Email ENDS WITH ANY OF [<1 hashed value>] => false, skipping the remaining AND conditions
13 | THEN 'private' => cannot evaluate, User Object is missing
14 | The current targeting rule is ignored and the evaluation continues with the next rule.
15 | - IF User.Country IS ONE OF [<1 hashed value>] => false, skipping the remaining AND conditions
16 | THEN 'target' => cannot evaluate, User Object is missing
17 | The current targeting rule is ignored and the evaluation continues with the next rule.
18 | Prerequisite flag evaluation result: 'public'.
19 | Condition (Flag 'mainFeature' EQUALS 'public') evaluates to true.
20 | )
21 | THEN % options => MATCH, applying rule
22 | Skipping % options because the User Object is missing.
23 | The current targeting rule is ignored and the evaluation continues with the next rule.
24 | - IF Flag 'mainFeature' EQUALS 'public'
25 | (
26 | Evaluating prerequisite flag 'mainFeature':
27 | Evaluating targeting rules and applying the first match if any:
28 | - IF User.Email ENDS WITH ANY OF [<1 hashed value>] => false, skipping the remaining AND conditions
29 | THEN 'private' => cannot evaluate, User Object is missing
30 | The current targeting rule is ignored and the evaluation continues with the next rule.
31 | - IF User.Country IS ONE OF [<1 hashed value>] => false, skipping the remaining AND conditions
32 | THEN 'target' => cannot evaluate, User Object is missing
33 | The current targeting rule is ignored and the evaluation continues with the next rule.
34 | Prerequisite flag evaluation result: 'public'.
35 | Condition (Flag 'mainFeature' EQUALS 'public') evaluates to true.
36 | )
37 | THEN 'Frog' => MATCH, applying rule
38 | Returning 'Frog'.
39 |
--------------------------------------------------------------------------------
/src/test/resources/evaluation/comparators/allinone.txt:
--------------------------------------------------------------------------------
1 | INFO [5000] Evaluating 'allinone' for User '{"Identifier":"12345","Email":"joe@example.com","Country":"[\"USA\"]","Date":"1693497500","Number":"1.0","Version":"1.0.0"}'
2 | Evaluating targeting rules and applying the first match if any:
3 | - IF User.Email EQUALS '' => true
4 | AND User.Email NOT EQUALS '' => false, skipping the remaining AND conditions
5 | THEN '1h' => no match
6 | - IF User.Email EQUALS 'joe@example.com' => true
7 | AND User.Email NOT EQUALS 'joe@example.com' => false, skipping the remaining AND conditions
8 | THEN '1c' => no match
9 | - IF User.Email IS ONE OF [<1 hashed value>] => true
10 | AND User.Email IS NOT ONE OF [<1 hashed value>] => false, skipping the remaining AND conditions
11 | THEN '2h' => no match
12 | - IF User.Email IS ONE OF ['joe@example.com'] => true
13 | AND User.Email IS NOT ONE OF ['joe@example.com'] => false, skipping the remaining AND conditions
14 | THEN '2c' => no match
15 | - IF User.Email STARTS WITH ANY OF [<1 hashed value>] => true
16 | AND User.Email NOT STARTS WITH ANY OF [<1 hashed value>] => false, skipping the remaining AND conditions
17 | THEN '3h' => no match
18 | - IF User.Email STARTS WITH ANY OF ['joe@'] => true
19 | AND User.Email NOT STARTS WITH ANY OF ['joe@'] => false, skipping the remaining AND conditions
20 | THEN '3c' => no match
21 | - IF User.Email ENDS WITH ANY OF [<1 hashed value>] => true
22 | AND User.Email NOT ENDS WITH ANY OF [<1 hashed value>] => false, skipping the remaining AND conditions
23 | THEN '4h' => no match
24 | - IF User.Email ENDS WITH ANY OF ['@example.com'] => true
25 | AND User.Email NOT ENDS WITH ANY OF ['@example.com'] => false, skipping the remaining AND conditions
26 | THEN '4c' => no match
27 | - IF User.Email CONTAINS ANY OF ['e@e'] => true
28 | AND User.Email NOT CONTAINS ANY OF ['e@e'] => false, skipping the remaining AND conditions
29 | THEN '5' => no match
30 | - IF User.Version IS ONE OF ['1.0.0'] => true
31 | AND User.Version IS NOT ONE OF ['1.0.0'] => false, skipping the remaining AND conditions
32 | THEN '6' => no match
33 | - IF User.Version < '1.0.1' => true
34 | AND User.Version >= '1.0.1' => false, skipping the remaining AND conditions
35 | THEN '7' => no match
36 | - IF User.Version > '0.9.9' => true
37 | AND User.Version <= '0.9.9' => false, skipping the remaining AND conditions
38 | THEN '8' => no match
39 | - IF User.Number = '1' => true
40 | AND User.Number != '1' => false, skipping the remaining AND conditions
41 | THEN '9' => no match
42 | - IF User.Number < '1.1' => true
43 | AND User.Number >= '1.1' => false, skipping the remaining AND conditions
44 | THEN '10' => no match
45 | - IF User.Number > '0.9' => true
46 | AND User.Number <= '0.9' => false, skipping the remaining AND conditions
47 | THEN '11' => no match
48 | - IF User.Date BEFORE '1693497600' (2023-08-31T16:00:00.000Z UTC) => true
49 | AND User.Date AFTER '1693497600' (2023-08-31T16:00:00.000Z UTC) => false, skipping the remaining AND conditions
50 | THEN '12' => no match
51 | - IF User.Country ARRAY CONTAINS ANY OF [<1 hashed value>] => true
52 | AND User.Country ARRAY NOT CONTAINS ANY OF [<1 hashed value>] => false, skipping the remaining AND conditions
53 | THEN '13h' => no match
54 | - IF User.Country ARRAY CONTAINS ANY OF ['USA'] => true
55 | AND User.Country ARRAY NOT CONTAINS ANY OF ['USA'] => false, skipping the remaining AND conditions
56 | THEN '13c' => no match
57 | Returning 'default'.
58 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/UserAttributeConverter.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import java.text.DecimalFormat;
4 | import java.text.DecimalFormatSymbols;
5 | import java.util.Date;
6 | import java.util.List;
7 | import java.util.Locale;
8 |
9 | final class UserAttributeConverter {
10 |
11 | public static String userAttributeToString(Object userAttribute) {
12 | if (userAttribute == null) {
13 | return null;
14 | }
15 | if (userAttribute instanceof String) {
16 | return (String) userAttribute;
17 | }
18 | if (userAttribute instanceof String[]) {
19 | return Utils.gson.toJson(userAttribute);
20 | }
21 | if (userAttribute instanceof List) {
22 | return Utils.gson.toJson(userAttribute);
23 | }
24 | if (userAttribute instanceof Date) {
25 | Date userAttributeDate = (Date) userAttribute;
26 | return doubleToString(DateTimeUtils.getUnixSeconds(userAttributeDate));
27 | }
28 | if (userAttribute instanceof Float) {
29 | return doubleToString(((Float) userAttribute).doubleValue());
30 | }
31 | if (userAttribute instanceof Double) {
32 | return doubleToString((Double) userAttribute);
33 | }
34 | return userAttribute.toString();
35 | }
36 |
37 | private static String doubleToString(Double doubleToString) {
38 |
39 | // Handle Double.NaN, Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY
40 | if (doubleToString.isNaN() || doubleToString.isInfinite()) {
41 | return doubleToString.toString();
42 | }
43 |
44 | // To get similar result between different SDKs the Double value format is modified.
45 | // Between 1e-6 and 1e21 we don't use scientific-notation. Over these limits scientific-notation used but the
46 | // ExponentSeparator replaced with "e" and "e+".
47 | // "." used as decimal separator in all cases.
48 | double abs = Math.abs(doubleToString);
49 | DecimalFormat fmt = 1e-6 <= abs && abs < 1e21
50 | ? new DecimalFormat("#.#################")
51 | : new DecimalFormat("#.#################E0");
52 | DecimalFormatSymbols SYMBOLS = DecimalFormatSymbols.getInstance(Locale.UK);
53 | if (abs > 1) {
54 | SYMBOLS.setExponentSeparator("e+");
55 | } else {
56 | SYMBOLS.setExponentSeparator("e");
57 | }
58 | fmt.setDecimalFormatSymbols(SYMBOLS);
59 | return fmt.format(doubleToString);
60 | }
61 |
62 | public static Double userAttributeToDouble(Object userAttribute) {
63 | if (userAttribute == null) {
64 | return null;
65 | }
66 | if (userAttribute instanceof Double) {
67 | return (Double) userAttribute;
68 | }
69 | if (userAttribute instanceof String) {
70 | return Double.parseDouble(((String) userAttribute).trim().replace(",", "."));
71 | }
72 | if (userAttribute instanceof Integer) {
73 | return ((Integer) userAttribute).doubleValue();
74 | }
75 | if (userAttribute instanceof Float) {
76 | return ((Float) userAttribute).doubleValue();
77 | }
78 | if (userAttribute instanceof Long) {
79 | return ((Long) userAttribute).doubleValue();
80 | }
81 | if (userAttribute instanceof Byte) {
82 | return ((Byte) userAttribute).doubleValue();
83 | }
84 | if (userAttribute instanceof Short) {
85 | return ((Short) userAttribute).doubleValue();
86 | }
87 |
88 | throw new NumberFormatException();
89 | }
90 |
91 | }
92 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/EvaluationDetails.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * Additional information about flag evaluation.
5 | */
6 | public class EvaluationDetails {
7 | private final T value;
8 | private final String key;
9 | private final String variationId;
10 | private final User user;
11 | private final boolean isDefaultValue;
12 | private final Object error;
13 | private final long fetchTimeUnixMilliseconds;
14 | private final TargetingRule matchedTargetingRule;
15 | private final PercentageOption matchedPercentageOption;
16 |
17 | public EvaluationDetails(T value,
18 | String key,
19 | String variationId,
20 | User user,
21 | boolean isDefaultValue,
22 | Object error,
23 | long fetchTimeUnixMilliseconds,
24 | TargetingRule matchedTargetingRule,
25 | PercentageOption matchedPercentageOption) {
26 | this.value = value;
27 | this.key = key;
28 | this.variationId = variationId;
29 | this.user = user;
30 | this.isDefaultValue = isDefaultValue;
31 | this.error = error;
32 | this.fetchTimeUnixMilliseconds = fetchTimeUnixMilliseconds;
33 | this.matchedTargetingRule = matchedTargetingRule;
34 | this.matchedPercentageOption = matchedPercentageOption;
35 | }
36 |
37 | static EvaluationDetails fromError(String key, T defaultValue, Object error, User user) {
38 | return new EvaluationDetails<>(defaultValue, key, "", user, true, error, Constants.DISTANT_PAST, null, null);
39 | }
40 |
41 | EvaluationDetails
asTypeSpecific() {
42 | return new EvaluationDetails<>((TR) value, key, variationId, user, isDefaultValue, error, fetchTimeUnixMilliseconds, matchedTargetingRule, matchedPercentageOption);
43 | }
44 |
45 | /**
46 | * The evaluated value of the feature flag or setting.
47 | */
48 | public T getValue() {
49 | return value;
50 | }
51 |
52 | /**
53 | * The key of the evaluated feature flag or setting.
54 | */
55 | public String getKey() {
56 | return key;
57 | }
58 |
59 | /**
60 | * The variationID is the identifier of the evaluated value. Usually used for analytics.
61 | */
62 | public String getVariationId() {
63 | return variationId;
64 | }
65 |
66 | /**
67 | * The user object that was used for evaluation.
68 | */
69 | public User getUser() {
70 | return user;
71 | }
72 |
73 | /**
74 | * True when the default value was returned, possibly due to an error.
75 | */
76 | public boolean isDefaultValue() {
77 | return isDefaultValue;
78 | }
79 |
80 | /**
81 | * In case of an error, this field contains the error message.
82 | */
83 | public String getError() {
84 | if(error != null) {
85 | return error.toString();
86 | }
87 | return null;
88 | }
89 |
90 | /**
91 | * The last fetch time of the config.json in unix milliseconds format.
92 | */
93 | public Long getFetchTimeUnixMilliseconds() {
94 | return fetchTimeUnixMilliseconds;
95 | }
96 |
97 | /**
98 | * If the evaluation was based on a targeting rule, this field contains that specific rule.
99 | */
100 | public TargetingRule getMatchedTargetingRule() {
101 | return matchedTargetingRule;
102 | }
103 |
104 | /**
105 | * If the evaluation was based on a percentage rule, this field contains that specific rule.
106 | */
107 | public PercentageOption getMatchedPercentageOption() {
108 | return matchedPercentageOption;
109 | }
110 | }
--------------------------------------------------------------------------------
/src/test/resources/matrix/testmatrix_semantic_2.csv:
--------------------------------------------------------------------------------
1 | Identifier;Email;Country;AppVersion;precedenceTests
2 | dontcare;;;1.9.1-1;< 1.9.1-2
3 | dontcare;;;1.9.1-2;< 1.9.1-10
4 | dontcare;;;1.9.1-10;< 1.9.1-10a
5 | dontcare;;;1.9.1-10a;< 1.9.1-1a
6 | dontcare;;;1.9.1-1a;< 1.9.1-alpha
7 | dontcare;;;1.9.1-alpha;< 1.9.99-alpha
8 | dontcare;;;1.9.99-alpha;= 1.9.99-alpha
9 | dontcare;;;1.9.99-alpha+build1;= 1.9.99-alpha
10 | dontcare;;;1.9.99-alpha+build2;= 1.9.99-alpha
11 | dontcare;;;1.9.99-alpha2;< 1.9.99-beta
12 | dontcare;;;1.9.99-beta;< 1.9.99-rc
13 | dontcare;;;1.9.99-rc;< 1.9.99-rc.1
14 | dontcare;;;1.9.99-rc.1;< 1.9.99-rc.2
15 | dontcare;;;1.9.99-rc.2;< 1.9.99-rc.20
16 | dontcare;;;1.9.99-rc.9;< 1.9.99-rc.20
17 | dontcare;;;1.9.99-rc.20;< 1.9.99-rc.20a
18 | dontcare;;;1.9.99-rc.20a;< 1.9.99-rc.2a
19 | dontcare;;;1.9.99-rc.2a;< 1.9.99
20 | dontcare;;;1.9.99;< 1.9.100
21 | dontcare;;;1.9.100;< 1.10.0-alpha
22 | dontcare;;;1.10.0-alpha;<= 1.10.0-alpha
23 | dontcare;;;1.10.0;<= 1.10.0
24 | dontcare;;;1.10.1;<= 1.10.1
25 | dontcare;;;1.10.2;<= 1.10.3
26 | dontcare;;;2.0.0;= 2.0.0
27 | dontcare;;;2.0.0+build3;= 2.0.0
28 | dontcare;;;2.0.0+001;= 2.0.0
29 | dontcare;;;2.0.0+20130313144700;= 2.0.0
30 | dontcare;;;2.0.0+exp.sha.5114f85;= 2.0.0
31 | dontcare;;;3.0.0;= 3.0.0+build3
32 | dontcare;;;4.0.0;= 4.0.0+001
33 | dontcare;;;5.0.0;= 5.0.0+20130313144700
34 | dontcare;;;6.0.0;= 6.0.0+exp.sha.5114f85
35 | dontcare;;;7.0.0-patch+metadata;= 7.0.0-patch
36 | dontcare;;;8.0.0-patch+metadata;= 8.0.0-patch+anothermetadata
37 | dontcare;;;9.0.0-patch;= 9.0.0-patch+metadata
38 | dontcare;;;10.0.0;DEFAULT-FROM-CC-APP
39 | dontcare;;;104.0.0;> 103.0.0
40 | dontcare;;;103.0.0;>= 103.0.0
41 | dontcare;;;102.0.0;>= 101.0.0
42 | dontcare;;;101.0.0;>= 101.0.0
43 | dontcare;;;90.104.0;> 90.103.0
44 | dontcare;;;90.103.0;>= 90.103.0
45 | dontcare;;;90.102.0;>= 90.101.0
46 | dontcare;;;90.101.0;>= 90.101.0
47 | dontcare;;;80.0.104;> 80.0.103
48 | dontcare;;;80.0.103;>= 80.0.103
49 | dontcare;;;80.0.102;>= 80.0.101
50 | dontcare;;;80.0.101;>= 80.0.101
51 | dontcare;;;73.0.0;>= 73.0.0-beta.2
52 | dontcare;;;72.0.0;> 72.0.0-beta.2
53 | dontcare;;;72.0.0-beta.2;> 72.0.0-beta.1
54 | dontcare;;;72.0.0-beta.1;> 72.0.0-beta
55 | dontcare;;;72.0.0-beta;> 72.0.0-alpha
56 | dontcare;;;72.0.0-alpha;> 72.0.0-1a
57 | dontcare;;;72.0.0-1a;> 72.0.0-10a
58 | dontcare;;;72.0.0-10aa;> 72.0.0-10a
59 | dontcare;;;72.0.0-10a;> 72.0.0-2
60 | dontcare;;;72.0.0-2;> 72.0.0-1
61 | dontcare;;;71.0.0+metadata;>= 71.0.0+anothermetadata
62 | dontcare;;;71.0.0-patch3+metadata;>= 71.0.0-patch3+anothermetadata
63 | dontcare;;;71.0.0-patch2+metadata;>= 71.0.0-patch2
64 | dontcare;;;71.0.0-patch1;>= 71.0.0-patch1+metadata
65 | dontcare;;;60.73.0;>= 60.73.0-beta.2
66 | dontcare;;;60.72.0;> 60.72.0-beta.2
67 | dontcare;;;60.72.0-beta.2;> 60.72.0-beta.1
68 | dontcare;;;60.72.0-beta.1;> 60.72.0-beta
69 | dontcare;;;60.72.0-beta;> 60.72.0-alpha
70 | dontcare;;;60.72.0-alpha;> 60.72.0-1a
71 | dontcare;;;60.72.0-1a;> 60.72.0-10a
72 | dontcare;;;60.72.0-10aa;> 60.72.0-10a
73 | dontcare;;;60.72.0-10a;> 60.72.0-2
74 | dontcare;;;60.72.0-2;> 60.72.0-1
75 | dontcare;;;60.71.0+metadata;>= 60.71.0+anothermetadata
76 | dontcare;;;60.71.0-patch3+metadata;>= 60.71.0-patch3+anothermetadata
77 | dontcare;;;60.71.0-patch2+metadata;>= 60.71.0-patch2
78 | dontcare;;;60.71.0-patch1;>= 60.71.0-patch1+metadata
79 | dontcare;;;50.60.73;>= 50.60.73-beta.2
80 | dontcare;;;50.60.72;> 50.60.72-beta.2
81 | dontcare;;;50.60.72-beta.2;> 50.60.72-beta.1
82 | dontcare;;;50.60.72-beta.1;> 50.60.72-beta
83 | dontcare;;;50.60.72-beta;> 50.60.72-alpha
84 | dontcare;;;50.60.72-alpha;> 50.60.72-1a
85 | dontcare;;;50.60.72-1a;> 50.60.72-10a
86 | dontcare;;;50.60.72-10aa;> 50.60.72-10a
87 | dontcare;;;50.60.72-10a;> 50.60.72-2
88 | dontcare;;;50.60.72-2;> 50.60.72-1
89 | dontcare;;;50.60.71+metadata;>= 50.60.71+anothermetadata
90 | dontcare;;;50.60.71-patch3+metadata;>= 50.60.71-patch3+anothermetadata
91 | dontcare;;;50.60.71-patch2+metadata;>= 50.60.71-patch2
92 | dontcare;;;50.60.71-patch1;>= 50.60.71-patch1+metadata
93 | dontcare;;;50.60.71-patch1+anothermetadata;>= 50.60.71-patch1+metadata
94 | dontcare;;;40.0.0-patch;>= 40.0.0-patch
95 | dontcare;;;30.0.0-beta;>= 30.0.0-alpha
96 |
--------------------------------------------------------------------------------
/src/main/java/com/configcat/PollingModes.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | /**
4 | * Describes the polling modes.
5 | */
6 | public final class PollingModes {
7 | private PollingModes() { /* prevent from instantiating */ }
8 |
9 | /**
10 | * Set up the auto polling mode with default parameters.
11 | *
12 | * @return the auto polling mode.
13 | */
14 | public static PollingMode autoPoll() {
15 | return new AutoPollingMode(60, 5);
16 | }
17 |
18 | /**
19 | * Set up the auto polling mode with custom parameters.
20 | *
21 | * @param autoPollIntervalInSeconds Sets how often the config.json should be fetched and cached.
22 | * @return the auto polling mode.
23 | */
24 | public static PollingMode autoPoll(int autoPollIntervalInSeconds) {
25 | return new AutoPollingMode(autoPollIntervalInSeconds, 5);
26 | }
27 |
28 | /**
29 | * Set up the auto polling mode with custom parameters.
30 | *
31 | * @param autoPollIntervalInSeconds Sets how often the config.json should be fetched and cached.
32 | * @param maxInitWaitTimeSeconds Sets the time limit between the initialization of the client and the first config.json acquisition.
33 | * @return the auto polling mode.
34 | */
35 | public static PollingMode autoPoll(int autoPollIntervalInSeconds, int maxInitWaitTimeSeconds) {
36 | return new AutoPollingMode(autoPollIntervalInSeconds, maxInitWaitTimeSeconds);
37 | }
38 |
39 | /**
40 | * Set up a lazy polling mode with default parameters.
41 | *
42 | * @return the lazy polling mode.
43 | */
44 | public static PollingMode lazyLoad() {
45 | return new LazyLoadingMode(60);
46 | }
47 |
48 | /**
49 | * Set up a lazy polling mode with custom parameters.
50 | *
51 | * @param cacheRefreshIntervalInSeconds Sets how long the cache will store its value before fetching the latest from the network again.
52 | * @return the lazy polling mode.
53 | */
54 | public static PollingMode lazyLoad(int cacheRefreshIntervalInSeconds) {
55 | return new LazyLoadingMode(cacheRefreshIntervalInSeconds);
56 | }
57 |
58 | /**
59 | * Set up the manual polling mode.
60 | *
61 | * @return the manual polling mode.
62 | */
63 | public static PollingMode manualPoll() {
64 | return new ManualPollingMode();
65 | }
66 | }
67 |
68 | class AutoPollingMode implements PollingMode {
69 | private final int autoPollRateInSeconds;
70 | private final int maxInitWaitTimeSeconds;
71 |
72 | AutoPollingMode(int autoPollRateInSeconds, int maxInitWaitTimeSeconds) {
73 | if (autoPollRateInSeconds < 1)
74 | throw new IllegalArgumentException("autoPollRateInSeconds cannot be less than 1 second");
75 |
76 | this.autoPollRateInSeconds = autoPollRateInSeconds;
77 | this.maxInitWaitTimeSeconds = maxInitWaitTimeSeconds;
78 | }
79 |
80 | int getAutoPollRateInSeconds() {
81 | return autoPollRateInSeconds;
82 | }
83 |
84 | public int getMaxInitWaitTimeSeconds() {
85 | return maxInitWaitTimeSeconds;
86 | }
87 |
88 | @Override
89 | public String getPollingIdentifier() {
90 | return "a";
91 | }
92 | }
93 |
94 | class LazyLoadingMode implements PollingMode {
95 | private final int cacheRefreshIntervalInSeconds;
96 |
97 | LazyLoadingMode(int cacheRefreshIntervalInSeconds) {
98 | if (cacheRefreshIntervalInSeconds < 1)
99 | throw new IllegalArgumentException("cacheRefreshIntervalInSeconds cannot be less than 1 second");
100 |
101 | this.cacheRefreshIntervalInSeconds = cacheRefreshIntervalInSeconds;
102 | }
103 |
104 | int getCacheRefreshIntervalInSeconds() {
105 | return cacheRefreshIntervalInSeconds;
106 | }
107 |
108 | @Override
109 | public String getPollingIdentifier() {
110 | return "l";
111 | }
112 | }
113 |
114 | class ManualPollingMode implements PollingMode {
115 | @Override
116 | public String getPollingIdentifier() {
117 | return "m";
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/src/test/java/com/configcat/EntrySerializationTest.java:
--------------------------------------------------------------------------------
1 | package com.configcat;
2 |
3 | import org.junit.jupiter.api.Test;
4 |
5 | import static org.junit.jupiter.api.Assertions.*;
6 |
7 | public class EntrySerializationTest {
8 |
9 | private static final String TEST_JSON = "{ p: { s: 'test-salt'}, f: { fakeKey: { v: { s: %s }, t: %s, p: [], r: [] } } }";
10 |
11 | private static final String SERIALIZED_DATA = "%s\n%s\n%s";
12 |
13 | @Test
14 | void serialize() {
15 | String json = String.format(TEST_JSON, "test", "1");
16 | Config config = Utils.gson.fromJson(json, Config.class);
17 | long fetchTime = System.currentTimeMillis();
18 | Entry entry = new Entry(config, "fakeTag", json, fetchTime);
19 |
20 | String serializedString = entry.serialize();
21 |
22 | assertEquals(String.format(SERIALIZED_DATA, fetchTime, "fakeTag", json), serializedString);
23 | }
24 |
25 | @Test
26 | void payloadSerializationPlatformIndependent() {
27 | String payloadTestConfigJson = "{\"p\":{\"u\":\"https://cdn-global.configcat.com\",\"r\":0,\"s\": \"test-salt\"},\"f\":{\"testKey\":{\"v\":{\"s\":\"testValue\"},\"t\":1,\"p\":[],\"r\":[]}}}";
28 |
29 | Config config = Utils.gson.fromJson(payloadTestConfigJson, Config.class);
30 | Entry entry = new Entry(config, "test-etag", payloadTestConfigJson, 1686756435844L);
31 | String serializedString = entry.serialize();
32 |
33 | assertEquals("1686756435844\ntest-etag\n" + payloadTestConfigJson, serializedString);
34 | }
35 |
36 | @Test
37 | void deserialize() {
38 | String json = String.format(TEST_JSON, "test", "1");
39 | long currentTimeMillis = System.currentTimeMillis();
40 |
41 | Entry entry = Entry.fromString(String.format(SERIALIZED_DATA, currentTimeMillis, "fakeTag", json));
42 |
43 | assertNotNull(entry);
44 | assertEquals("fakeTag", entry.getETag());
45 | assertEquals(json, entry.getConfigJson());
46 | assertEquals(1, entry.getConfig().getEntries().size());
47 | assertEquals(currentTimeMillis, entry.getFetchTime());
48 | }
49 |
50 | @Test
51 | void deserializeMissingValue() {
52 | Entry deserializeNull = Entry.fromString(null);
53 | assertTrue(deserializeNull.isEmpty());
54 | Entry deserializeEmpty = Entry.fromString("");
55 | assertTrue(deserializeEmpty.isEmpty());
56 | }
57 |
58 | @Test
59 | void deserializeWrongFormat() {
60 | Exception assertThrows = assertThrows(Exception.class, () -> Entry.fromString("value with no new line"));
61 | assertEquals("Number of values is fewer than expected.", assertThrows.getMessage());
62 |
63 | assertThrows = assertThrows(Exception.class, () -> Entry.fromString("value with one \n new line"));
64 | assertEquals("Number of values is fewer than expected.", assertThrows.getMessage());
65 | }
66 |
67 | @Test
68 | void deserializeInvalidDate() {
69 | Exception assertThrows = assertThrows(Exception.class, () -> Entry.fromString(String.format(SERIALIZED_DATA, "invalid", "fakeTag", "json")));
70 |
71 | assertEquals("Invalid fetch time: invalid", assertThrows.getMessage());
72 | }
73 |
74 | @Test
75 | void deserializeInvalidETag() {
76 | long currentTimeMillis = System.currentTimeMillis();
77 | Exception assertThrows = assertThrows(Exception.class, () -> Entry.fromString(String.format(SERIALIZED_DATA, currentTimeMillis / 1000, "", "json")));
78 |
79 | assertEquals("Empty eTag value.", assertThrows.getMessage());
80 | }
81 |
82 | @Test
83 | void deserializeInvalidJson() {
84 | long currentTimeMillis = System.currentTimeMillis();
85 | Exception assertThrows = assertThrows(Exception.class, () -> Entry.fromString(String.format(SERIALIZED_DATA, currentTimeMillis / 1000, "fakeTag", "")));
86 |
87 | assertEquals("Empty config jsom value.", assertThrows.getMessage());
88 |
89 | assertThrows = assertThrows(Exception.class, () -> Entry.fromString(String.format(SERIALIZED_DATA, currentTimeMillis / 1000, "fakeTag", "wrongjson")));
90 |
91 | assertEquals("Invalid config JSON content: wrongjson", assertThrows.getMessage());
92 |
93 | }
94 |
95 | }
--------------------------------------------------------------------------------
/.github/workflows/android-ci.yml:
--------------------------------------------------------------------------------
1 | name: Android CI
2 |
3 | on:
4 | push:
5 | branches: [ master ]
6 | tags: [ 'v[0-9]+.[0-9]+.[0-9]+' ]
7 |
8 | workflow_dispatch:
9 |
10 | jobs:
11 | test:
12 | runs-on: ubuntu-latest
13 | strategy:
14 | matrix:
15 | java-versions: [ 17 ]
16 | steps:
17 | - uses: actions/checkout@v6
18 |
19 | - name: Set up JDK
20 | uses: actions/setup-java@v5
21 | with:
22 | java-version: ${{ matrix.java-versions }}
23 | distribution: zulu
24 |
25 | - name: Cache Gradle packages
26 | uses: actions/cache@v5
27 | with:
28 | path: ~/.gradle/caches
29 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
30 | restore-keys: ${{ runner.os }}-gradle
31 |
32 | - name: Grant execute permission for gradlew
33 | run: chmod +x gradlew
34 |
35 | - name: Test with Gradle
36 | run: ./gradlew test
37 |
38 | coverage-scan:
39 | runs-on: ubuntu-latest
40 | steps:
41 | - uses: actions/checkout@v6
42 | with:
43 | fetch-depth: 0
44 |
45 | - name: Set up JDK
46 | uses: actions/setup-java@v5
47 | with:
48 | java-version: 17
49 | distribution: zulu
50 |
51 | - name: Cache SonarCloud packages
52 | uses: actions/cache@v5
53 | with:
54 | path: ~/.sonar/cache
55 | key: ${{ runner.os }}-sonar
56 | restore-keys: ${{ runner.os }}-sonar
57 |
58 | - name: Cache Gradle packages
59 | uses: actions/cache@v5
60 | with:
61 | path: ~/.gradle/caches
62 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
63 | restore-keys: ${{ runner.os }}-gradle
64 |
65 | - name: Grant execute permission for gradlew
66 | run: chmod +x gradlew
67 |
68 | - name: Check with Gradle
69 | run: ./gradlew check
70 |
71 | - name: Execute sonar scan
72 | run: ./gradlew sonar -Dbuild.number=$GITHUB_RUN_NUMBER
73 | env:
74 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
75 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
76 |
77 | deploy-snapshot:
78 | needs: [ coverage-scan, test ]
79 | if: ${{ github.ref == 'refs/heads/master' }}
80 | runs-on: ubuntu-latest
81 | steps:
82 | - uses: actions/checkout@v6
83 |
84 | - name: Set up JDK
85 | uses: actions/setup-java@v5
86 | with:
87 | java-version: 17
88 | distribution: zulu
89 |
90 | - name: Cache Gradle packages
91 | uses: actions/cache@v5
92 | with:
93 | path: ~/.gradle/caches
94 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
95 | restore-keys: ${{ runner.os }}-gradle
96 |
97 | - name: Grant execute permission for gradlew
98 | run: chmod +x gradlew
99 |
100 | - name: Deploy snapshot with Gradle
101 | run: ./gradlew publishAllPublicationsToMavenCentralRepository -Dsnapshot=true
102 | env:
103 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_USERNAME }}
104 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_PASSWORD }}
105 | ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_PRIVATE_KEY }}
106 | ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.PASSPHRASE }}
107 |
108 | deploy-release:
109 | needs: [ coverage-scan, test ]
110 | if: startsWith(github.ref, 'refs/tags')
111 | runs-on: ubuntu-latest
112 | steps:
113 | - uses: actions/checkout@v6
114 |
115 | - name: Set up JDK
116 | uses: actions/setup-java@v5
117 | with:
118 | java-version: 17
119 | distribution: zulu
120 |
121 | - name: Cache Gradle packages
122 | uses: actions/cache@v5
123 | with:
124 | path: ~/.gradle/caches
125 | key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }}
126 | restore-keys: ${{ runner.os }}-gradle
127 |
128 | - name: Grant execute permission for gradlew
129 | run: chmod +x gradlew
130 |
131 | - name: Deploy release with Gradle
132 | run: ./gradlew publishToMavenCentral --no-configuration-cache
133 | env:
134 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_USERNAME }}
135 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_PASSWORD }}
136 | ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_PRIVATE_KEY }}
137 | ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.PASSPHRASE }}
138 |
--------------------------------------------------------------------------------
/src/test/resources/matrix/testmatrix_semantic.csv:
--------------------------------------------------------------------------------
1 | Identifier;Email;Country;Custom1;isOneOf;isOneOfWithPercentage;isNotOneOf;isNotOneOfWithPercentage;lessThanWithPercentage;relations
2 | ##null##;;;;Default;Default;Default;Default;Default;Default
3 | id1;;;0.0.0;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );< 1.0.0;< 1.0.0
4 | id1;;;0.1.0;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );< 1.0.0;< 1.0.0
5 | id1;;;0.2.1;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );< 1.0.0;< 1.0.0
6 | id1;;;1;Default;80%;Default;80%;20%;Default
7 | id2;;;1.0;Default;80%;Default;80%;80%;Default
8 | id3;;;1.0.0;Is one of (1.0.0);is one of (1.0.0);Default;80%;80%;<=1.0.0
9 | id4;;;1.0.0.0;Default;80%;Default;20%;20%;Default
10 | id5;;;1.0.0.0.0;Default;80%;Default;80%;80%;Default
11 | id6;;;1.0.1;Default;80%;Is not one of (1.0.0, 3.0.1);Is not one of (1.0.0, 3.0.1);80%;Default
12 | id7;;;1.0.11;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );20%;Default
13 | id8;;;1.0.111;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;Default
14 | id9;;;1.0.2;Default;20%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;Default
15 | id10;;;1.0.3;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;Default
16 | id11;;;1.0.4;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;Default
17 | id12;;;1.0.5;Default;20%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;Default
18 | id13;;;1.1.0;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;Default
19 | id14;;;1.1.1;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;Default
20 | id15;;;1.1.2;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;Default
21 | id16;;;1.1.3;Default;20%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );20%;Default
22 | id17;;;1.1.4;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );20%;Default
23 | id18;;;1.1.5;Default;20%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;Default
24 | id19;;;1.9.0;Default;20%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;Default
25 | id20;;;1.9.99;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );20%;Default
26 | id21;;;2.0.0;Default;80%;Is not one of (1.0.0, 3.0.1);Is not one of (1.0.0, 3.0.1);20%;>=2.0.0
27 | id22;;;2.0.1;Is one of ( , 2.0.1, 2.0.2, );80%;Is not one of (1.0.0, 3.0.1);Is not one of (1.0.0, 3.0.1);80%;>2.0.0
28 | id23;;;2.0.11;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );20%;>2.0.0
29 | id24;;;2.0.2;Is one of ( , 2.0.1, 2.0.2, );80%;Is not one of (1.0.0, 3.0.1);Is not one of (1.0.0, 3.0.1);80%;>2.0.0
30 | id25;;;2.0.3;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;>2.0.0
31 | id26;;;3.0.0;Is one of (3.0.0);80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;>2.0.0
32 | id27;;;3.0.1;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );20%;>2.0.0
33 | id28;;;3.1.0;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;>2.0.0
34 | id28;;;3.1.1;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;>2.0.0
35 | id29;;;5.0.0;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );80%;>2.0.0
36 | id30;;;5.99.999;Default;80%;Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );Is not one of (1.0.0, 1.0.1, 2.0.0 , 2.0.1, 2.0.2, );20%;>2.0.0
--------------------------------------------------------------------------------