Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,24 @@

import com.github.switcherapi.client.utils.SwitcherUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SnapshotCallback {

private static final Logger logger = LogManager.getLogger(SnapshotCallback.class);
public interface SnapshotCallback {

/**
* Callback method that will be invoked when the snapshot is updated
*
* @param version of the new snapshot
*/
public void onSnapshotUpdate(long version) {
SwitcherUtils.debug(logger, "Snapshot updated: {}", version);
default void onSnapshotUpdate(long version) {
SwitcherUtils.debug(LogManager.getLogger(SnapshotCallback.class), "Snapshot updated: {}", version);
}

/**
* Callback method that will be invoked when the snapshot update fails
*
* @param e Exception
*/
public void onSnapshotUpdateError(Exception e) {
SwitcherUtils.debug(logger, "Failed to update snapshot: {}", e.getMessage());
default void onSnapshotUpdateError(Exception e) {
SwitcherUtils.debug(LogManager.getLogger(SnapshotCallback.class), "Failed to update snapshot: {}", e.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ public static boolean scheduleSnapshotAutoUpdate(String intervalValue, SnapshotC
}

final long interval = SwitcherUtils.getMillis(intervalValue);
final SnapshotCallback callbackFinal = Optional.ofNullable(callback).orElse(new SnapshotCallback());
final SnapshotCallback callbackFinal = Optional.ofNullable(callback).orElse(new SnapshotCallback() {});
final Runnable runnableSnapshotValidate = () -> {
try {
if (validateSnapshot()) {
Expand Down Expand Up @@ -270,19 +270,31 @@ public static boolean validateSnapshot() {
/**
* Start watching snapshot files for modifications.<br>
* When the file is modified the in-memory snapshot will reload
*
* <p>
* (*) Requires client to use local settings
*/
public static void watchSnapshot() {
watchSnapshot(new SnapshotEventHandler());
watchSnapshot(new SnapshotEventHandler() {});
}

/**
* Start watching snapshot files for modifications.<br>
* When the file is modified the in-memory snapshot will reload
*
* <p>
* (*) Requires client to use local settings
*
* @param handler to notify snapshot change events
* @throws SwitcherException if using remote service
*/
public static void watchSnapshot(SnapshotEventHandler handler) {
SwitcherUtils.watchSnapshot(instance, handler);
if (!(instance instanceof SwitcherLocalService)) {
throw new SwitcherException("Cannot watch snapshot when using remote", new UnsupportedOperationException());
}

SwitcherLocalService executorInstance = (SwitcherLocalService) instance;
SwitcherUtils.watchSnapshot(executorInstance, handler);
}

/**
Expand Down
11 changes: 0 additions & 11 deletions src/main/java/com/github/switcherapi/client/SwitcherExecutor.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import com.github.switcherapi.client.model.criteria.Snapshot;
import com.github.switcherapi.client.model.response.CriteriaResponse;
import com.github.switcherapi.client.service.remote.ClientRemote;
import com.github.switcherapi.client.utils.SnapshotEventHandler;
import com.github.switcherapi.client.utils.SnapshotLoader;
import com.github.switcherapi.client.utils.SwitcherUtils;
import com.google.gson.Gson;
Expand Down Expand Up @@ -59,16 +58,6 @@ public abstract class SwitcherExecutor {
* @param switchers To be validated
*/
public abstract void checkSwitchers(final Set<String> switchers);

/**
* Update in-memory snapshot.
*
* @param snapshotFile Path location
* @param handler to notify snapshot change events
*
* @return true if valid change
*/
public abstract boolean notifyChange(final String snapshotFile, SnapshotEventHandler handler);

/**
* Retrieve local snapshot version
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,44 @@ public void init() {
}
}
}

/**
* Update in-memory snapshot.
*
* @param snapshotFile Path location
* @param handler to notify snapshot change events
*
* @return true if valid change
*/
public boolean notifyChange(final String snapshotFile, SnapshotEventHandler handler) {
final String environment = SwitcherContextBase.contextStr(ContextKey.ENVIRONMENT);
final String snapshotLocation = SwitcherContextBase.contextStr(ContextKey.SNAPSHOT_LOCATION);

try {
if (snapshotFile.equals(String.format("%s.json", environment))) {
SwitcherUtils.debug(logger, "Updating domain");

this.domain = SnapshotLoader.loadSnapshot(snapshotLocation, environment);
handler.onSuccess();
}
} catch (SwitcherSnapshotLoadException | IOException e) {
handler.onError(new SwitcherException(e.getMessage(), e));
logger.error(e);
return false;
}

return true;
}

/**
* Update in-memory snapshot.
*
* @param snapshotFile Path location
* @return true if valid change
*/
public boolean notifyChange(final String snapshotFile) {
return this.notifyChange(snapshotFile, new SnapshotEventHandler() {});
}

@Override
public CriteriaResponse executeCriteria(final Switcher switcher) {
Expand Down Expand Up @@ -111,27 +149,6 @@ public void checkSwitchers(final Set<String> switchers) {
throw new SwitchersValidationException(response.toString());
}
}

@Override
public boolean notifyChange(final String snapshotFile, SnapshotEventHandler handler) {
final String environment = SwitcherContextBase.contextStr(ContextKey.ENVIRONMENT);
final String snapshotLocation = SwitcherContextBase.contextStr(ContextKey.SNAPSHOT_LOCATION);

try {
if (snapshotFile.equals(String.format("%s.json", environment))) {
SwitcherUtils.debug(logger, "Updating domain");

this.domain = SnapshotLoader.loadSnapshot(snapshotLocation, environment);
handler.onSuccess();
}
} catch (SwitcherSnapshotLoadException | IOException e) {
handler.onError(new SwitcherException(e.getMessage(), e));
logger.error(e);
return false;
}

return true;
}

@Override
public long getSnapshotVersion() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
package com.github.switcherapi.client.service.remote;

import java.util.Arrays;
import java.util.Set;

import com.github.switcherapi.client.utils.SwitcherUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.github.switcherapi.client.SwitcherContextBase;
import com.github.switcherapi.client.SwitcherExecutor;
import com.github.switcherapi.client.exception.SwitcherRemoteException;
Expand All @@ -17,7 +9,13 @@
import com.github.switcherapi.client.model.criteria.SwitchersCheck;
import com.github.switcherapi.client.model.response.CriteriaResponse;
import com.github.switcherapi.client.service.local.SwitcherLocalService;
import com.github.switcherapi.client.utils.SnapshotEventHandler;
import com.github.switcherapi.client.utils.SwitcherUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Arrays;
import java.util.Set;

/**
* @author Roger Floriano (petruki)
Expand Down Expand Up @@ -95,11 +93,6 @@ public void checkSwitchers(final Set<String> switchers) {
throw new SwitchersValidationException(Arrays.toString(response.getNotFound()));
}
}

@Override
public boolean notifyChange(String snapshotFile, SnapshotEventHandler handler) {
return this.switcherLocal.notifyChange(snapshotFile, handler);
}

@Override
public long getSnapshotVersion() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package com.github.switcherapi.client.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.github.switcherapi.client.exception.SwitcherException;
import org.apache.logging.log4j.LogManager;

/**
* Access snapshot event handler when a file is modified.<br>
Expand All @@ -12,16 +10,22 @@
* @author Roger Floriano (petruki)
* @since 2022-06-29
*/
public class SnapshotEventHandler {

private static final Logger logger = LogManager.getLogger(SnapshotEventHandler.class);

public void onSuccess() {
SwitcherUtils.debug(logger, "Snapshot has been changed");
public interface SnapshotEventHandler {

/**
* Callback method that will be invoked when the snapshot is updated
*/
default void onSuccess() {
SwitcherUtils.debug(LogManager.getLogger(SnapshotEventHandler.class), "Snapshot has been changed");
}

public void onError(SwitcherException exception) {
logger.error(exception);

/**
* Callback method that will be invoked when the snapshot update fails
*
* @param exception Exception
*/
default void onError(SwitcherException exception) {
LogManager.getLogger(SnapshotEventHandler.class).error(exception);
}

}
Original file line number Diff line number Diff line change
@@ -1,23 +1,17 @@
package com.github.switcherapi.client.utils;

import java.io.IOException;
import java.nio.file.ClosedWatchServiceException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

import com.github.switcherapi.client.SwitcherContextBase;
import com.github.switcherapi.client.model.ContextKey;
import com.github.switcherapi.client.service.local.SwitcherLocalService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.github.switcherapi.client.SwitcherContextBase;
import com.github.switcherapi.client.SwitcherExecutor;
import com.github.switcherapi.client.model.ContextKey;
import java.io.IOException;
import java.nio.file.*;

/**
* SnapshotWatcher runs in a separate thread to watch for changes in the snapshot file.
*
* @author Roger Floriano (petruki)
* @since 2020-05-13
*/
Expand All @@ -29,9 +23,9 @@ public class SnapshotWatcher implements Runnable {

private WatchService watcher;

private SwitcherExecutor executorInstance;
private SwitcherLocalService executorInstance;

public SnapshotWatcher(final SwitcherExecutor executorInstance, SnapshotEventHandler handler) {
public SnapshotWatcher(final SwitcherLocalService executorInstance, SnapshotEventHandler handler) {
this.executorInstance = executorInstance;
this.handler = handler;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package com.github.switcherapi.client.utils;

import com.github.switcherapi.client.SwitcherExecutor;
import com.github.switcherapi.client.exception.SwitcherContextException;
import com.github.switcherapi.client.exception.SwitcherInvalidDateTimeArgumentException;
import com.github.switcherapi.client.model.ContextKey;
import com.github.switcherapi.client.service.WorkerName;
import com.github.switcherapi.client.service.local.SwitcherLocalService;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
Expand Down Expand Up @@ -141,7 +141,7 @@ public static Set<String> payloadReader(String jsonStr, String prevKey) {
* @param executorInstance of a Remote or Local Switcher
* @param handler to notify snapshot change events
*/
public static void watchSnapshot(final SwitcherExecutor executorInstance, SnapshotEventHandler handler) {
public static void watchSnapshot(final SwitcherLocalService executorInstance, SnapshotEventHandler handler) {
if (watcher == null) {
watcher = new SnapshotWatcher(executorInstance, handler);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,15 @@ void shouldNotifyWithError() {
SwitchersBase.configure(ContextBuilder.builder()
.environment("defect_default"));

assertFalse(service.notifyChange("defect_default.json", new SnapshotEventHandler()));
assertFalse(service.notifyChange("defect_default.json"));
}

@Test
void shouldNotifyWithSuccess() {
SwitchersBase.configure(ContextBuilder.builder()
.environment("snapshot_watcher"));

assertTrue(service.notifyChange("snapshot_watcher.json", new SnapshotEventHandler()));
assertTrue(service.notifyChange("snapshot_watcher.json"));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.github.switcherapi.client.utils;

import com.github.switcherapi.SwitchersBase;
import com.github.switcherapi.client.ContextBuilder;
import com.github.switcherapi.client.exception.SwitcherException;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

class SnapshotWatcherErrorTest {

@Test
void shouldNotWatchSnapshotWhenRemote() {
//given
SwitchersBase.configure(ContextBuilder.builder()
.contextLocation(SwitchersBase.class.getCanonicalName())
.url("https://api.switcherapi.com")
.apiKey("[API_KEY]")
.domain("Test")
.component("switcher-test")
.local(false));

SwitchersBase.initializeClient();

//test
SwitcherException exception = assertThrows(SwitcherException.class, SwitchersBase::watchSnapshot);
assertEquals("Something went wrong: Cannot watch snapshot when using remote", exception.getMessage());
}
}