### FileBasedTogglzConfiguration Example
Source: https://www.togglz.org/documentation/repositories
Demonstrates how to configure Togglz to use the FileBasedStateRepository. It specifies the path to the properties file used for storing feature states.
```java
public class FileBasedTogglzConfiguration implements TogglzConfig {
/* ..... */
@Override
public StateRepository getStateRepository() {
return new FileBasedStateRepository(new File("/tmp/features.properties"));
}
}
```
--------------------------------
### Custom Weekday Activation Strategy Example
Source: https://www.togglz.org/documentation/activation-strategies
Implement a custom activation strategy that enables a feature only on specific days of the week. This strategy requires a 'day' parameter to be configured.
```java
public class WeekdayActivationStrategy implements ActivationStrategy {
private static final String[] SHORT_WEEKDAYS =
DateFormatSymbols.getInstance().getShortWeekdays();
@Override
public String getId() {
return "weekday";
}
@Override
public String getName() {
return "Weekday strategy";
}
@Override
public Parameter[] getParameters() {
return new Parameter[] {
ParameterBuilder.create("day").label("Day of week")
};
}
@Override
public boolean isActive(FeatureState featureState, FeatureUser user) {
// the weekday name configured for the strategy
String selectedWeekday = featureState.getParameter("day");
// get the weekday name for today
Calendar now = GregorianCalendar.getInstance();
int currentWeekday = now.get(Calendar.DAY_OF_WEEK);
String currentWeekdayName = SHORT_WEEKDAYS[currentWeekday];
// the feature is active if the weekday matches
return selectedWeekday.equals(currentWeekdayName);
}
}
```
--------------------------------
### CachingStateRepository Usage Example
Source: https://www.togglz.org/documentation/repositories
Demonstrates how to wrap an existing StateRepository with CachingStateRepository to add caching. The example shows setting a cache timeout in milliseconds.
```java
public class CachingTogglzConfiguration implements TogglzConfig {
/* ..... */
@Override
public StateRepository getStateRepository() {
StateRepository someOtherRepository = ...;
return new CachingStateRepository(someOtherRepository, 10000);
}
}
```
--------------------------------
### JDBCStateRepository Configuration with DataSource
Source: https://www.togglz.org/documentation/repositories
Shows how to configure Togglz to use the JDBCStateRepository by injecting a DataSource. This example uses JNDI lookup for the data source in a JEE environment.
```java
@ApplicationScoped
public class DatabaseTogglzConfiguration implements TogglzConfig {
@Resource(mappedName = "jboss/datasources/ExampleDS")
private DataSource dataSource;
/* ..... */
@Override
public StateRepository getStateRepository() {
return new JDBCStateRepository(dataSource);
}
}
```
--------------------------------
### Typical FeatureManager Configuration
Source: https://www.togglz.org/documentation/configuration
This example demonstrates a typical configuration for the Togglz FeatureManager by implementing the TogglzConfig interface. It specifies the feature enum class, configures a file-based state repository, and sets up a servlet user provider.
```java
import java.io.File;
import org.togglz.core.Feature;
import org.togglz.core.manager.TogglzConfig;
import org.togglz.core.repository.StateRepository;
import org.togglz.core.repository.file.FileBasedStateRepository;
import org.togglz.core.user.FeatureUser;
import org.togglz.core.user.UserProvider;
import org.togglz.servlet.user.ServletUserProvider
public class MyTogglzConfiguration implements TogglzConfig {
public Class extends Feature> getFeatureClass() {
return MyFeatures.class;
}
public StateRepository getStateRepository() {
return new FileBasedStateRepository(new File("/tmp/features.properties"));
}
public UserProvider getUserProvider() {
return new ServletUserProvider();
}
}
```
--------------------------------
### Script Engine Strategy Example
Source: https://www.togglz.org/documentation/activation-strategies
Use this script for the Script Engine strategy to activate a feature for a specific user on a particular day of the week. Ensure your script evaluates to a boolean.
```javascript
user.name == 'john' && date.day == 0
```
--------------------------------
### Get Feature Toggles via Actuator Endpoint
Source: https://www.togglz.org/documentation/spring-boot-starter
Use this curl command to retrieve the status of all feature toggles. The response provides a JSON array of toggle states.
```bash
curl -GET http://localhost:8080/actuator/togglz
```
--------------------------------
### Vary Feature States with JUnit 5 TestTemplate
Source: https://www.togglz.org/documentation/testing
Use @TestTemplate and @VaryFeatures with a VariationSetProvider to run tests with different feature combinations. This example enables ONE, disables TWO, and varies THREE.
```java
class FeatureVariationTogglzExtensionTest {
@TestTemplate
@VaryFeatures(TestingVariationSetProvider.class)
void variations() {
assertTrue(MyFeatures.ONE.isActive());
assertFalse(MyFeatures.TWO.isActive());
// active or not active, that is the question
assertTrue(MyFeatures.THREE.isActive() || !MyFeatures.THREE.isActive());
}
private static class TestingVariationSetProvider implements VariationSetProvider {
@Override
public VariationSet extends Feature> buildVariationSet() {
return create(MyFeatures.class).enable(MyFeatures.ONE).disable(MyFeatures.TWO).vary(MyFeatures.THREE);
}
}
}
```
--------------------------------
### Dummy UserProvider for Testing
Source: https://www.togglz.org/documentation/admin-console
Configure a dummy UserProvider that grants administration privileges to all users for testing purposes. Do not use this in production.
```java
public class MyTogglzConfiguration implements TogglzConfig {
/* ..... */
@Override
public UserProvider getUserProvider() {
return new UserProvider() {
@Override
public FeatureUser getCurrentUser() {
return new SimpleFeatureUser("admin", true);
}
};
}
}
```
--------------------------------
### Configure Togglz Class via web.xml (Servlet)
Source: https://www.togglz.org/documentation/configuration
In servlet environments without Spring or CDI, specify your TogglzConfig implementation class using a context-param in web.xml.
```xml
org.togglz.core.manager.TogglzConfig
com.example.myapp.MyTogglzConfiguration
```
--------------------------------
### Configure Features via application.yml
Source: https://www.togglz.org/documentation/spring-boot-starter
Configure feature flags using YAML format in `application.yml`. This provides a structured alternative to properties files.
```yaml
togglz:
features:
FOO:
enabled: true
BAR:
enabled: false
```
--------------------------------
### MongoStateRepository Builder Configuration
Source: https://www.togglz.org/documentation/repositories
Illustrates how to configure the MongoStateRepository using its builder pattern. It specifies the MongoClient, database name, and optionally the collection name and write concern.
```java
StateRepository stateRepository = MongoStateRepository.newBuilder(mongoClient, "myDatabase")
.collection('myFeatureState')
.writeConcern(WriteConcern.REPLICA_ACKNOWLEDGED)
.build();
```
--------------------------------
### Configure ServletUserProvider in TogglzConfig
Source: https://www.togglz.org/documentation/authentication
Implement TogglzConfig to use ServletUserProvider, specifying an admin role for console access. This is useful when integrating with container-managed authentication.
```java
public class MyTogglzConfiguration implements TogglzConfig {
/* ..... */
@Override
public UserProvider getUserProvider() {
return new ServletUserProvider("ADMIN_ROLE");
}
}
```
--------------------------------
### Configure TogglzConsoleServlet for Non-Servlet 3.0 Containers
Source: https://www.togglz.org/documentation/admin-console
Add this servlet configuration to your /WEB-INF/web.xml if your container does not support Servlet 3.0.
```xml
TogglzConsoleServlet
org.togglz.console.TogglzConsoleServlet
TogglzConsoleServlet
/togglz/*
```
--------------------------------
### Add togglz-seam-security Dependency
Source: https://www.togglz.org/documentation/authentication
Include this dependency to enable integration with Seam Security.
```xml
org.togglz
togglz-seam-security
3.1.2
```
--------------------------------
### Configure SpringSecurityUserProvider in TogglzConfig
Source: https://www.togglz.org/documentation/authentication
Implement the `TogglzConfig` interface to use `SpringSecurityUserProvider`. Specify an authority name for administrative access.
```java
public class MyTogglzConfiguration implements TogglzConfig {
/* ..... */
@Override
public UserProvider getUserProvider() {
return new SpringSecurityUserProvider("ADMIN_AUTHORITY");
}
}
```
--------------------------------
### Add Togglz Spring Boot Starter Dependency (Maven)
Source: https://www.togglz.org/documentation/spring-boot-starter
Include this dependency in your Maven project to enable Togglz auto-configuration for Spring Boot 2.x.
```xml
org.togglz
togglz-spring-boot-starter
3.1.2
```
--------------------------------
### Implement Custom User Provider in Java
Source: https://www.togglz.org/documentation/authentication
Implement a custom `UserProvider` by overriding `getUserProvider()` to read user information from servlet request attributes. Use `HttpServletRequestHolder` to access the request.
```java
public class MyTogglzConfiguration implements TogglzConfig {
/* ..... */
@Override
public UserProvider getUserProvider() {
return new UserProvider() {
@Override
public FeatureUser getCurrentUser() {
HttpServletRequest request = HttpServletRequestHolder.get();
String username = (String) request.getAttribute("username");
boolean isAdmin = "admin".equals(username);
return new SimpleFeatureUser(username, isAdmin);
}
};
}
}
```
--------------------------------
### Implement FeatureAdmin Authorizer for Seam Security
Source: https://www.togglz.org/documentation/authentication
Implement an authorizer method for @FeatureAdmin using Seam Security's Identity.
```java
public class SeamSecurityAuthorizer {
@Secures
@FeatureAdmin
public boolean isFeatureAdmin(Identity identity) {
// return true if the current user is allowed to toggle features
}
}
```
--------------------------------
### Build FeatureManager with TogglzConfig
Source: https://www.togglz.org/documentation/advanced-config
Use `FeatureManagerBuilder` to create a `FeatureManager` configured with a custom `TogglzConfig` implementation. This is similar to how Togglz bootstraps in web applications.
```java
FeatureManager manager = new FeatureManagerBuilder()
.togglzConfig(new MyTogglzConfig())
.build();
```
--------------------------------
### Add Togglz Spring Boot Starter Dependency (Gradle)
Source: https://www.togglz.org/documentation/spring-boot-starter
Add this dependency to your Gradle build file for Spring Boot 2.x integration with Togglz.
```gradle
implementation("org.togglz:togglz-spring-boot-starter:3.1.2")
```
--------------------------------
### Configure Togglz Application Properties
Source: https://www.togglz.org/documentation/spring-boot-starter
Use these properties in application.properties or application.yml to enable and configure Togglz features, caching, and the admin console.
```yaml
togglz:
enabled: true # Enable Togglz for the application.
feature-enums: # Comma-separated list of fully-qualified feature enum class names.
feature-manager-name: # The name of the feature manager.
features: # The feature states. Only needed if feature states are stored in application properties.
HELLO_WORLD:
enabled: true
REVERSE_GREETING:
enabled: true
strategy: username
param:
users: user2, user3
features-file: # The path to the features file that contains the feature states. Only needed if feature states are stored in external properties file.
features-file-min-check-interval: # The minimum amount of time in milliseconds to wait between checks of the file's modification date.
cache:
enabled: false # Enable feature state caching.
time-to-live: 0 # The time after which a cache entry will expire.
time-unit: milliseconds # The time unit as java.util.concurrent.TimeUnit enum name (one of "nanoseconds", "microseconds", "milliseconds", "seconds", "minutes", "hours", "days").
console:
enabled: true # Enable admin console.
path: /togglz-console # The path of the admin console when enabled.
feature-admin-authority: ROLE_ADMIN # The name of the authority that is allowed to access the admin console.
secured: true # Indicates if the admin console runs in secured mode. If false the application itself should take care of securing the admin console.
use-management-port: true # Indicates if the admin console runs on the management port. If no management port is configured it will run on the application port. If set to true the console path will also be prefixed with the management.context-path.
endpoint: # Only for Spring Boot 1.x (for Spring Boot 2.x see https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html)
id: togglz # The endpoint identifier.
enabled: true # Enable actuator endpoint.
sensitive: true # Indicates if the endpoint exposes sensitive information.
```
--------------------------------
### Register ThreadLocalUserProvider in TogglzConfig
Source: https://www.togglz.org/documentation/authentication
Configure Togglz to use `ThreadLocalUserProvider` by returning an instance from the `getUserProvider` method in your `TogglzConfig` implementation.
```java
public class MyTogglzConfiguration implements TogglzConfig {
/* ..... */
@Override
public UserProvider getUserProvider() {
return new ThreadLocalUserProvider();
}
}
```
--------------------------------
### Build FeatureManager with Builder Methods
Source: https://www.togglz.org/documentation/advanced-config
Configure a `FeatureManager` directly using `FeatureManagerBuilder` methods without implementing `TogglzConfig`. This allows setting the feature class, state repository, and user provider.
```java
FeatureManager manager = new FeatureManagerBuilder()
.featureClass(MyFeaturess.class)
.stateRepository(new InMemoryStateRepository())
.userProvider(new NoOpUserProvider())
.build();
```
--------------------------------
### Singleton FeatureManagerProvider for Standalone Apps
Source: https://www.togglz.org/documentation/advanced-config
Implement FeatureManagerProvider using a singleton pattern for standalone Java applications. This approach ensures a single instance of FeatureManager is managed.
```java
public class SingletonFeatureManagerProvider implements FeatureManagerProvider {
private static FeatureManager featureManager;
@Override
public int priority() {
return 30;
}
@Override
public synchronized FeatureManager getFeatureManager() {
if (featureManager == null) {
featureManager = new FeatureManagerBuilder()
.featureClass(MyFeaturess.class)
.stateRepository(new InMemoryStateRepository())
.userProvider(new NoOpUserProvider())
.build();
}
return featureManager;
}
}
```
--------------------------------
### Configure SeamSecurityUserProvider in TogglzConfig
Source: https://www.togglz.org/documentation/authentication
Register the SeamSecurityUserProvider in your TogglzConfig to use Seam Security integration.
```java
public class MyTogglzConfiguration implements TogglzConfig {
/* ..... */
@Override
public UserProvider getUserProvider() {
return new SeamSecurityUserProvider();
}
}
```
--------------------------------
### Configure DeltaSpikeUserProvider in TogglzConfig
Source: https://www.togglz.org/documentation/authentication
Register the DeltaSpikeUserProvider in your TogglzConfig to use DeltaSpike Identity integration.
```java
public class MyTogglzConfiguration implements TogglzConfig {
/* ..... */
@Override
public UserProvider getUserProvider() {
return new DeltaSpikeUserProvider();
}
}
```
--------------------------------
### Bind User in Servlet Filter with ThreadLocalUserProvider
Source: https://www.togglz.org/documentation/authentication
In a servlet filter, create a `FeatureUser` and bind it using `ThreadLocalUserProvider.bind(user)` before proceeding with the filter chain. Ensure to release the user in a finally block.
```java
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String username = ...;
boolean isAdmin = ...;
FeatureUser user = new SimpleFeatureUser(username, isAdmin);
ThreadLocalUserProvider.bind(user);
try {
chain.doFilter(request, response);
} finally {
ThreadLocalUserProvider.release();
}
}
```
--------------------------------
### FileBasedStateRepository Properties Format
Source: https://www.togglz.org/documentation/repositories
Defines the format for feature state properties files used by FileBasedStateRepository. Features can be enabled/disabled, and activation strategies with parameters can be specified.
```properties
# The feature 'FEATURE_ONE' is disabled
FEATURE_ONE=false
# The feature 'FEATURE_TWO' is enabled for the users 'chkal' and 'john'
FEATURE_TWO=true
FEATURE_TWO.strategy = username
FEATURE_TWO.param.users = chkal, john
```
--------------------------------
### FeatureManagerProvider using EJB Singleton
Source: https://www.togglz.org/documentation/advanced-config
Implement FeatureManagerProvider to obtain FeatureManager from an EJB singleton via JNDI lookup. Handles NamingException if lookup fails.
```java
public class EJBSingletonFeatureManagerProvider implements FeatureManagerProvider {
@Override
public int priority() {
return 30;
}
@Override
public FeatureManager getFeatureManager() {
try {
InitialContext context = new InitialContext();
FeatureManagerSingleton singleton = (FeatureManagerSingleton)
context.lookup("java:module/FeatureManagerSingleton");
return singleton.getFeatureManager();
} catch (NamingException e) {
return null;
}
}
}
```
--------------------------------
### Running Tests with FeatureVariations
Source: https://www.togglz.org/documentation/testing
Annotate your test class with @RunWith(FeatureVariations.class) and provide a VariationSet via a @Variations annotated method to execute tests with different feature state combinations. This helps verify code behavior across various feature toggles.
```java
@RunWith(FeatureVariations.class)
public class FeatureVariationsTest {
@Variations
public static VariationSet getPermutations() {
return VariationSetBuilder.create(MyFeatures.class)
.enable(MyFeatures.F1)
.vary(MyFeatures.F2)
.vary(MyFeatures.F3);
}
// will be executed 4 times
@Test
public void test() {
assertTrue(MyFeatures.F1.isActive());
assertTrue(MyFeatures.F2.isActive() || !MyFeatures.F2.isActive());
assertTrue(MyFeatures.F3.isActive() || !MyFeatures.F3.isActive());
}
}
```
--------------------------------
### Configure Features via application.properties
Source: https://www.togglz.org/documentation/spring-boot-starter
Enable or disable features using Spring environment properties in `application.properties`. This is a common way to manage feature flags.
```properties
togglz.features.FOO.enabled=true
toggltz.features.BAR.enabled=false
```
--------------------------------
### Annotate Togglz Configuration with @Component (Spring)
Source: https://www.togglz.org/documentation/configuration
When using Spring, annotate your TogglzConfig implementation with @Component to have it managed by the Spring ApplicationContext.
```java
import org.springframework.stereotype.Component;
import org.togglz.core.TogglzConfig;
@Component
public class MyTogglzConfiguration implements TogglzConfig {
// code
}
```
--------------------------------
### Togglz Filter for Servlet 2.5 and earlier
Source: https://www.togglz.org/documentation/installation
Declare this filter in your /WEB-INF/web.xml if your container does not support the Servlet 3.0 specification.
```xml
TogglzFilter
org.togglz.servlet.TogglzFilter
TogglzFilter
/*
```
--------------------------------
### Add Togglz Admin Console Dependency
Source: https://www.togglz.org/documentation/admin-console
Include this Maven dependency to add the Togglz admin console to your project.
```xml
org.togglz
togglz-console
3.1.2
```
--------------------------------
### Add Togglz Testing Support Dependency
Source: https://www.togglz.org/documentation/testing
Add this dependency to your project's test scope to enable Togglz testing support. This configuration ensures all features are active by default during unit tests.
```xml
org.togglz
togglz-testing
3.1.2
test
```
--------------------------------
### Add togglz-deltaspike Dependency
Source: https://www.togglz.org/documentation/authentication
Include this dependency to enable integration with Apache DeltaSpike Identity.
```xml
org.togglz
togglz-deltaspike
3.1.2
```
--------------------------------
### JSF Integration for Feature Rendering
Source: https://www.togglz.org/documentation/usage
Conditionally render page content based on feature activation using JSF. This is useful for progressive rollouts or A/B testing.
```html
```
--------------------------------
### Add Optional Togglz Modules (Gradle)
Source: https://www.togglz.org/documentation/spring-boot-starter
Add these optional dependencies to your Gradle build file for Togglz Admin Console, Spring Security integration, and Thymeleaf support.
```gradle
implementation("org.togglz:togglz-console:3.1.2")
implementation("org.togglz:togglz-spring-security:3.1.2")
implementation("com.github.heneke.thymeleaf:thymeleaf-extras-togglz:1.0.1.RELEASE")
```
--------------------------------
### Provide Features via EnumBasedFeatureProvider
Source: https://www.togglz.org/documentation/spring-boot-starter
Register an enum-based feature provider as a Spring bean to make features defined in the enum available to Togglz.
```java
@Bean
public FeatureProvider featureProvider() {
return new EnumBasedFeatureProvider(MyFeatures.class);
}
```
--------------------------------
### Define Features with Annotations
Source: https://www.togglz.org/documentation/configuration
Implement a Java enum that extends the Feature interface to declare your application's features. Use annotations like @Label and @EnabledByDefault to configure feature metadata and default states.
```java
import org.togglz.core.Feature;
import org.togglz.core.annotation.EnabledByDefault;
import org.togglz.core.annotation.Label;
import org.togglz.core.context.FeatureContext;
public enum MyFeatures implements Feature {
@EnabledByDefault
@Label("First Feature")
FEATURE_ONE,
@Label("Second Feature")
FEATURE_TWO;
public boolean isActive() {
return FeatureContext.getFeatureManager().isActive(this);
}
}
```
--------------------------------
### Add Optional Togglz Modules (Maven)
Source: https://www.togglz.org/documentation/spring-boot-starter
Include these optional dependencies for Togglz Admin Console, Spring Security integration, and Thymeleaf support in your Maven project.
```xml
org.togglz
togglz-console
3.1.2
org.togglz
togglz-spring-security
3.1.2
com.github.heneke.thymeleaf
thymeleaf-extras-togglz
1.0.1.RELEASE
```
--------------------------------
### Togglz Maven Dependencies
Source: https://www.togglz.org/documentation/installation
Add these dependencies to your Maven project for Togglz integration. The core and servlet modules are mandatory for web applications.
```xml
org.togglz
togglz-core
3.1.2
org.togglz
togglz-servlet
3.1.2
org.togglz
togglz-cdi
3.1.2
org.togglz
togglz-spring-web
3.1.2
org.togglz
togglz-jsf
3.1.2
```
--------------------------------
### Configure FeatureProxyFactoryBean in Spring
Source: https://www.togglz.org/documentation/usage
Use FeatureProxyFactoryBean to create a proxy that delegates calls to different beans based on feature activation. Ensure the proxied beans share a common interface.
```xml
```
--------------------------------
### Add Togglz JUnit Dependency
Source: https://www.togglz.org/documentation/testing
Include the togloz-junit module in your test dependencies for JUnit support.
```xml
org.togglz
togglz-junit
3.1.2
test
```
--------------------------------
### Add Spring Security Togglz Dependency
Source: https://www.togglz.org/documentation/authentication
Include this Maven dependency to enable Togglz integration with Spring Security.
```xml
org.togglz
togglz-spring-security
3.1.2
```
--------------------------------
### Enable/Disable Feature Toggle via Actuator Endpoint
Source: https://www.togglz.org/documentation/spring-boot-starter
Use this curl command with a POST request to change the enabled state of a specific feature toggle. Ensure the Content-Type header is set to application/json.
```bash
curl -d '{"name":"REVERSE_GREETING", "enabled":"true"}' -H "Content-Type: application/json" -POST http://localhost:8080/actuator/togglz/GREETING
```
--------------------------------
### Using TogglzRule for Runtime Feature State Modification
Source: https://www.togglz.org/documentation/testing
The TogglzRule allows modifying feature states at runtime, useful for testing specific feature combinations. Initialize the rule with static methods like allEnabled() and use its methods to alter feature states.
```java
public class SomeJunitTest {
@Rule
public TogglzRule togglzRule = TogglzRule.allEnabled(MyFeatures.class);
@Test
public void testToggleFeature() {
// all features are active by default
assertTrue(MyFeatures.FEATURE_ONE.isActive());
// you can easily modify the feature state using the TogglzRule
togglzRule.disable(MyFeatures.FEATURE_ONE);
assertFalse(MyFeatures.FEATURE_ONE.isActive());
}
}
```
--------------------------------
### Add Spring Integration Dependency
Source: https://www.togglz.org/documentation/usage
Include the Spring integration module for advanced Togglz features in your Spring applications. Ensure this dependency is added to your project.
```xml
org.togglz
togglz-spring-web
3.1.2
```
--------------------------------
### EJB Singleton for FeatureManager in JEE
Source: https://www.togglz.org/documentation/advanced-config
Manage FeatureManager using an EJB singleton in JEE environments. The FeatureManager is built during the @PostConstruct phase.
```java
@Singleton
public class FeatureManagerSingleton {
private FeatureManager featureManager;
@PostConstruct
public void init() {
featureManager = new FeatureManagerBuilder()
.featureClass(MyFeaturess.class)
.stateRepository(new InMemoryStateRepository())
.userProvider(new NoOpUserProvider())
.build();
}
public FeatureManager getFeatureManager() {
return featureManager;
}
}
```
--------------------------------
### Check Feature Activation in Java
Source: https://www.togglz.org/documentation/usage
Check if a feature is active using the isActive() method on the corresponding enum. No complex lookups are required.
```java
if (MyFeatures.HOT_NEW_FEATURE.isActive()) {
// do cool new stuff here
}
```
--------------------------------
### Prevent Default FeatureManager Creation in Web Applications
Source: https://www.togglz.org/documentation/advanced-config
Configure web.xml to prevent Togglz from automatically creating a local FeatureManager in web applications. This allows a shared FeatureManager to be used.
```xml
org.togglz.FEATURE_MANAGER_PROVIDED
true
```
--------------------------------
### Check Feature Activation Status
Source: https://www.togglz.org
Check if a specific feature is enabled for the current user by calling the isActive() method on the feature enum constant.
```java
public void someBusinessMethod() {
if( MyFeatures.FEATURE_ONE.isActive() ) {
// do new exciting stuff here
}
[...]
}
```
--------------------------------
### Inject FeatureManager in Spring Boot Application
Source: https://www.togglz.org/documentation/spring-boot-starter
Demonstrates how to inject the `FeatureManager` into a Spring controller to check feature activation status. Constructor injection is used, and `@Autowired` is optional for Spring 4.3+.
```java
@Controller
public class MyClass {
private FeatureManager manager;
public static final Feature HELLO_WORLD = new NamedFeature("HELLO_WORLD");
public MyClass(FeatureManager manager) {
this.manager = manager;
}
@RequestMapping("/")
public ResponseEntity> index() {
if (manager.isActive(HELLO_WORLD)) {
...
}
}
}
```
--------------------------------
### Test All Features Enabled with JUnit 5
Source: https://www.togglz.org/documentation/testing
Use the @AllEnabled annotation to ensure all features in a given enum are active for a test.
```java
class AnnotationBasedTogglzExtensionTest {
@Test
@AllEnabled(MyFeatures.class)
void allEnabled() {
assertTrue(MyFeatures.ONE.isActive());
assertTrue(MyFeatures.TWO.isActive());
assertTrue(MyFeatures.THREE.isActive());
}
```
--------------------------------
### Define Custom Feature Group Annotation
Source: https://www.togglz.org/documentation/feature-groups
Create a custom annotation for feature groups. The custom annotation must be annotated with @FeatureGroup. The @Label annotation is optional for setting a custom display name.
```java
@FeatureGroup
@Label("Performance Improvements")
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Performance {
// no content
}
```
--------------------------------
### Assign Features to Groups
Source: https://www.togglz.org/documentation/feature-groups
Add features to a group by either applying the @FeatureGroup annotation with the group name to the feature enum constant or by using a custom feature group annotation.
```java
public enum MyFeatures implements Feature {
@Label("Enable database caching")
@Performance
DATABASE_CACHING,
@FeatureGroup("Performance Improvements")
PERFORMANCE_IMPROVEMENTS,
@Label("Some other one")
OTHER_FEATURE;
/* ... */
}
```
--------------------------------
### Define Features with Java Enum
Source: https://www.togglz.org
Declare features using a Java enum that implements the Feature interface. Each enum constant represents a feature.
```java
public enum MyFeatures implements Feature {
@Label("First Feature")
FEATURE_ONE,
@Label("Second Feature")
FEATURE_TWO;
public boolean isActive() {
return FeatureContext.getFeatureManager().isActive(this);
}
}
```
--------------------------------
### Define Features with Java Enum
Source: https://www.togglz.org/documentation/overview
Declare features using a Java enum. Annotations like @Label and @ActiveByDefault can enrich feature metadata. The isActive() method checks feature status.
```java
public enum MyFeatures implements Feature {
@Label("First Feature")
FEATURE_ONE,
@Label("Second Feature")
@ActiveByDefault
FEATURE_TWO;
public boolean isActive() {
return FeatureContext.getFeatureManager().isActive(this);
}
}
```
--------------------------------
### Define Feature Group with @FeatureGroup Annotation
Source: https://www.togglz.org/documentation/feature-groups
Use the @FeatureGroup annotation directly on a feature enum constant to assign it to a group. The group name is provided as a string parameter.
```java
@FeatureGroup("Performance Improvements")
```
--------------------------------
### Test All Features Disabled with JUnit 5
Source: https://www.togglz.org/documentation/testing
Use the @AllDisabled annotation to ensure all features in a given enum are inactive for a test.
```java
class AnnotationBasedTogglzExtensionTest {
@Test
@AllDisabled(MyFeatures.class)
void allDisabled() {
assertFalse(MyFeatures.ONE.isActive());
assertFalse(MyFeatures.TWO.isActive());
assertFalse(MyFeatures.THREE.isActive());
}
```
--------------------------------
### Control Specific Features with TestFeatureManager
Source: https://www.togglz.org/documentation/testing
Inject TestFeatureManager to enable or disable specific features within a test method. Requires @AllEnabled or @AllDisabled annotation on the test method.
```java
class AnnotationBasedTogglzExtensionTest {
@Test
@AllEnabled(MyFeatures.class)
void testFeatureManagerParameter(TestFeatureManager featureManager) {
assertTrue(MyFeatures.ONE.isActive());
featureManager.disable(MyFeatures.ONE);
assertFalse(MyFeatures.ONE.isActive());
featureManager.enable(MyFeatures.ONE);
assertTrue(MyFeatures.ONE.isActive());
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.