From a9a4cc467cc69b12232b76cd3b004059de9c7073 Mon Sep 17 00:00:00 2001 From: petruki <31597636+petruki@users.noreply.github.com> Date: Wed, 27 Nov 2024 17:24:43 -0800 Subject: [PATCH 1/3] Adding support to native app --- README.md | 10 +- pom.xml | 1 + .../switcherapi/client/SwitcherConfig.java | 31 ++++ .../client/SwitcherContextBase.java | 46 +++-- .../switcherapi/client/SwitcherExecutor.java | 39 ++-- .../client/model/AsyncSwitcher.java | 9 +- .../switcherapi/client/model/Switcher.java | 58 ++---- .../client/model/SwitcherBuilder.java | 17 +- .../client/model/SwitcherInterface.java | 34 ++-- ...teriaResponse.java => SwitcherResult.java} | 46 +++-- .../criteria/{Criteria.java => Data.java} | 2 +- .../client/model/criteria/Snapshot.java | 6 +- .../switcherapi/client/remote/ClientWS.java | 15 +- .../client/remote/ClientWSImpl.java | 19 +- .../response => remote/dto}/AuthRequest.java | 2 +- .../response => remote/dto}/AuthResponse.java | 2 +- .../client/remote/dto/CriteriaRequest.java | 63 +++++++ .../client/remote/dto/CriteriaResponse.java | 59 ++++++ .../dto}/SnapshotVersionResponse.java | 2 +- .../dto}/SwitchersCheck.java | 2 +- .../client/service/local/ClientLocal.java | 4 +- .../service/local/ClientLocalService.java | 28 +-- .../service/local/SwitcherLocalService.java | 11 +- .../client/service/remote/ClientRemote.java | 10 +- .../service/remote/ClientRemoteService.java | 11 +- .../service/remote/SwitcherRemoteService.java | 20 +- .../client/test/SwitcherTestExtension.java | 14 +- .../client/utils/SnapshotLoader.java | 34 +++- .../client/utils/SwitcherUtils.java | 48 ++--- .../switcher-client/reflect-config.json | 175 ++++++++++++++++++ .../switcher-client/resource-config.json | 18 ++ .../switcherapi/SwitchersBaseNative.java | 24 +++ .../SwitcherBasicCriteriaResponseTest.java | 10 +- .../client/SwitcherBypassTest.java | 20 +- .../client/SwitcherConfigNativeTest.java | 44 +++-- .../client/SwitcherLocal1Test.java | 5 +- .../SwitcherSnapshotAutoUpdateTest.java | 8 +- .../SwitcherSnapshotValidationTest.java | 2 +- .../switcherapi/client/model/ModelTest.java | 10 +- .../client/remote/ClientRemoteTest.java | 10 +- .../local/SwitcherLocalServiceTest.java | 18 ++ .../client/utils/SnapshotWatcherTest.java | 16 +- .../client/utils/SwitcherUtilsTest.java | 1 + .../fixture/MockWebServerHelper.java | 20 +- .../playground/ClientPlayground.java | 17 +- .../switcherapi/playground/Features.java | 14 ++ 46 files changed, 744 insertions(+), 311 deletions(-) rename src/main/java/com/github/switcherapi/client/model/{response/CriteriaResponse.java => SwitcherResult.java} (61%) rename src/main/java/com/github/switcherapi/client/model/criteria/{Criteria.java => Data.java} (91%) rename src/main/java/com/github/switcherapi/client/{model/response => remote/dto}/AuthRequest.java (93%) rename src/main/java/com/github/switcherapi/client/{model/response => remote/dto}/AuthResponse.java (88%) create mode 100644 src/main/java/com/github/switcherapi/client/remote/dto/CriteriaRequest.java create mode 100644 src/main/java/com/github/switcherapi/client/remote/dto/CriteriaResponse.java rename src/main/java/com/github/switcherapi/client/{model/response => remote/dto}/SnapshotVersionResponse.java (82%) rename src/main/java/com/github/switcherapi/client/{model/criteria => remote/dto}/SwitchersCheck.java (94%) create mode 100644 src/main/resources/META-INF/native-image/com.github.switcherapi.client/switcher-client/reflect-config.json create mode 100644 src/main/resources/META-INF/native-image/com.github.switcherapi.client/switcher-client/resource-config.json create mode 100644 src/test/java/com/github/switcherapi/SwitchersBaseNative.java diff --git a/README.md b/README.md index 62eed593..a2e6d629 100644 --- a/README.md +++ b/README.md @@ -154,13 +154,13 @@ Switcher switcher = MyAppFeatures.getSwitcher(FEATURE01); switcher.isItOn(); ``` -Or, you can submit the switcher request and get the criteria response, which contains result, reason and metadata that can be used for any additional verification. +Or, you can submit the switcher request and get the switcher result, which contains result, reason and metadata that can be used for any additional verification. ```java -CriteriaResponse response = switcher.submit(); -response.isItOn(); // true/false -response.getReason(); // Descriptive response based on result value -response.getMetadata(YourMetadata.class); // Additional information +SwitcherResult result = switcher.submit(); +result.isItOn(); // true/false +result.getReason(); // Descriptive response based on result value +result.getMetadata(YourMetadata.class); // Additional information ``` 2. **Strategy validation - preparing input** diff --git a/pom.xml b/pom.xml index 1eda9252..1b6b5ea2 100644 --- a/pom.xml +++ b/pom.xml @@ -80,6 +80,7 @@ java **/model/**/*.java, + **/remote/dto/*.java, **/exception/**/*.java, **/service/validators/RegexValidatorV8.java, **/client/remote/Constants.java diff --git a/src/main/java/com/github/switcherapi/client/SwitcherConfig.java b/src/main/java/com/github/switcherapi/client/SwitcherConfig.java index c1623a43..a400e43a 100644 --- a/src/main/java/com/github/switcherapi/client/SwitcherConfig.java +++ b/src/main/java/com/github/switcherapi/client/SwitcherConfig.java @@ -1,5 +1,7 @@ package com.github.switcherapi.client; +import com.github.switcherapi.client.model.ContextKey; + abstract class SwitcherConfig { protected String url; @@ -20,6 +22,35 @@ abstract class SwitcherConfig { this.truststore = new TruststoreConfig(); } + /** + * Update Switcher Configurations state using pre-configured properties. + * + * @param properties Switcher Properties + */ + protected void updateSwitcherConfig(SwitcherProperties properties) { + setUrl(properties.getValue(ContextKey.URL)); + setApikey(properties.getValue(ContextKey.APIKEY)); + setDomain(properties.getValue(ContextKey.DOMAIN)); + setComponent(properties.getValue(ContextKey.COMPONENT)); + setEnvironment(properties.getValue(ContextKey.ENVIRONMENT)); + setLocal(properties.getBoolean(ContextKey.LOCAL_MODE)); + setSilent(properties.getValue(ContextKey.SILENT_MODE)); + setTimeout(properties.getInt(ContextKey.TIMEOUT_MS)); + setPoolSize(properties.getInt(ContextKey.POOL_CONNECTION_SIZE)); + + SnapshotConfig snapshot = new SnapshotConfig(); + snapshot.setLocation(properties.getValue(ContextKey.SNAPSHOT_LOCATION)); + snapshot.setAuto(properties.getBoolean(ContextKey.SNAPSHOT_AUTO_LOAD)); + snapshot.setSkipValidation(properties.getBoolean(ContextKey.SNAPSHOT_SKIP_VALIDATION)); + snapshot.setUpdateInterval(properties.getValue(ContextKey.SNAPSHOT_AUTO_UPDATE_INTERVAL)); + setSnapshot(snapshot); + + TruststoreConfig truststore = new TruststoreConfig(); + truststore.setPath(properties.getValue(ContextKey.TRUSTSTORE_PATH)); + truststore.setPassword(properties.getValue(ContextKey.TRUSTSTORE_PASSWORD)); + setTruststore(truststore); + } + /** * Initialize the Switcher Client.
* - Build context {@link ContextBuilder}
diff --git a/src/main/java/com/github/switcherapi/client/SwitcherContextBase.java b/src/main/java/com/github/switcherapi/client/SwitcherContextBase.java index 1818c6ef..98d56cc9 100644 --- a/src/main/java/com/github/switcherapi/client/SwitcherContextBase.java +++ b/src/main/java/com/github/switcherapi/client/SwitcherContextBase.java @@ -73,7 +73,6 @@ * * Features.initializeClient(); * } - * * * * @see SwitcherKey @@ -118,21 +117,28 @@ protected void configureClient() { .truststorePath(truststore.getPath()) .truststorePassword(truststore.getPassword())); - switcherProperties.setValue(ContextKey.CONTEXT_LOCATION, contextBase.getClass().getName()); initializeClient(); } @Override protected void configureClient(String contextFile) { setContextBase(this); - loadProperties(contextFile); + loadProperties(contextFile); switcherProperties.setValue(ContextKey.CONTEXT_LOCATION, contextBase.getClass().getName()); + + updateSwitcherConfig(switcherProperties); initializeClient(); } - private static synchronized void setContextBase(SwitcherContextBase contextBase) { - SwitcherContextBase.contextBase = contextBase; + /** + * Manually register Switcher Keys.
+ * Use this method before calling {@link #configureClient()} to register the Switcher Keys. + * + * @param switcherKeys to be registered + */ + protected void registerSwitcherKeys(String... switcherKeys) { + setSwitcherKeys(new HashSet<>(Arrays.asList(switcherKeys))); } /** @@ -172,7 +178,7 @@ public static void loadProperties(String contextFilename) { */ public static void initializeClient() { validateContext(); - validateSwitcherKeys(); + registerSwitcherKeys(); instance = buildInstance(); loadSwitchers(); @@ -194,9 +200,10 @@ private static SwitcherExecutor buildInstance() { if (contextBol(ContextKey.LOCAL_MODE)) { return new SwitcherLocalService(clientRemote, clientLocal, switcherProperties); - } else { - return new SwitcherRemoteService(clientRemote, new SwitcherLocalService(clientRemote, clientLocal, switcherProperties)); } + + return new SwitcherRemoteService(clientRemote, new SwitcherLocalService(clientRemote, + clientLocal, switcherProperties)); } /** @@ -211,10 +218,9 @@ private static void validateContext() throws SwitcherContextException { } /** - * Validate Switcher Keys.
- * It will ensure that only properly annotated Switchers can be used. + * Register Switcher Keys based on context properties */ - private static void validateSwitcherKeys() { + private static void registerSwitcherKeys() { if (Objects.nonNull(contextBase)) { registerSwitcherKey(contextBase.getClass().getFields()); } else { @@ -233,7 +239,7 @@ private static void validateSwitcherKeys() { * @param fields to be registered */ private static void registerSwitcherKey(Field[] fields) { - switcherKeys = new HashSet<>(); + switcherKeys = Optional.ofNullable(switcherKeys).orElse(new HashSet<>()); for (Field field : fields) { if (field.isAnnotationPresent(SwitcherKey.class)) { switcherKeys.add(field.getName()); @@ -245,7 +251,7 @@ private static void registerSwitcherKey(Field[] fields) { * Load Switcher instances into a map cache */ private static void loadSwitchers() { - if (switchers == null) { + if (Objects.isNull(switchers)) { switchers = new HashMap<>(); } @@ -413,7 +419,7 @@ public static void watchSnapshot(SnapshotEventHandler handler) { throw new SwitcherException("Cannot watch snapshot when using remote", new UnsupportedOperationException()); } - if (watcherSnapshot == null) { + if (Objects.isNull(watcherSnapshot)) { watcherSnapshot = new SnapshotWatcher((SwitcherLocalService) instance, handler, contextStr(ContextKey.SNAPSHOT_LOCATION)); } @@ -428,7 +434,7 @@ public static void watchSnapshot(SnapshotEventHandler handler) { * @throws SwitcherException if watch thread never started */ public static void stopWatchingSnapshot() { - if (watcherSnapshot != null) { + if (Objects.nonNull(watcherSnapshot)) { watcherExecutorService.shutdownNow(); watcherSnapshot.terminate(); watcherSnapshot = null; @@ -496,10 +502,18 @@ public static void configure(ContextBuilder builder) { * Cancel existing scheduled task for updating local Snapshot */ public static void terminateSnapshotAutoUpdateWorker() { - if (scheduledExecutorService != null) { + if (Objects.nonNull(scheduledExecutorService)) { scheduledExecutorService.shutdownNow(); scheduledExecutorService = null; } } + + private static synchronized void setContextBase(SwitcherContextBase contextBase) { + SwitcherContextBase.contextBase = contextBase; + } + + private static synchronized void setSwitcherKeys(Set switcherKeys) { + SwitcherContextBase.switcherKeys = switcherKeys; + } } diff --git a/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java b/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java index 1f10e2d5..20b2e4f8 100644 --- a/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java +++ b/src/main/java/com/github/switcherapi/client/SwitcherExecutor.java @@ -6,7 +6,7 @@ import com.github.switcherapi.client.model.Switcher; import com.github.switcherapi.client.model.criteria.Domain; import com.github.switcherapi.client.model.criteria.Snapshot; -import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.model.SwitcherResult; import com.github.switcherapi.client.service.remote.ClientRemote; import com.github.switcherapi.client.utils.SnapshotLoader; import com.github.switcherapi.client.utils.SwitcherUtils; @@ -17,6 +17,7 @@ import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Set; /** @@ -30,7 +31,7 @@ public abstract class SwitcherExecutor { private static final Logger logger = LoggerFactory.getLogger(SwitcherExecutor.class); - private static final Map bypass = new HashMap<>(); + private static final Map bypass = new HashMap<>(); protected final SwitcherProperties switcherProperties; @@ -46,7 +47,7 @@ protected SwitcherExecutor(final SwitcherProperties switcherProperties) { * @param switcher to be evaluated * @return Criteria response containing the evaluation details */ - public abstract CriteriaResponse executeCriteria(final Switcher switcher); + public abstract SwitcherResult executeCriteria(final Switcher switcher); /** * Check the snapshot versions against the Remote configuration. @@ -77,10 +78,10 @@ protected SwitcherExecutor(final SwitcherProperties switcherProperties) { protected boolean checkSnapshotVersion(ClientRemote clientRemote, final Domain domain) { final String environment = switcherProperties.getValue(ContextKey.ENVIRONMENT); SwitcherUtils.debug(logger, "verifying snapshot version - environment: {}", environment); - + return clientRemote.checkSnapshotVersion(domain.getVersion()); } - + protected Domain initializeSnapshotFromAPI(ClientRemote clientRemote) throws SwitcherRemoteException, SwitcherSnapshotWriteException { final String environment = switcherProperties.getValue(ContextKey.ENVIRONMENT); @@ -89,25 +90,21 @@ protected Domain initializeSnapshotFromAPI(ClientRemote clientRemote) final Snapshot snapshot = clientRemote.resolveSnapshot(); final String snapshotLocation = switcherProperties.getValue(ContextKey.SNAPSHOT_LOCATION); - if (snapshotLocation != null) { + if (Objects.nonNull(snapshotLocation)) { SnapshotLoader.saveSnapshot(snapshot, snapshotLocation, environment); } return snapshot.getDomain(); } - - public boolean isLocalEnabled() { - return switcherProperties.getBoolean(ContextKey.LOCAL_MODE); - } /** * It manipulates the result of a given Switcher key. * * @param key name of the key that you want to change the result * @param expectedResult that will be returned when performing isItOn - * @return CriteriaResponse with the manipulated result + * @return SwitcherResult with the manipulated result */ - public static CriteriaResponse assume(final String key, boolean expectedResult) { + public static SwitcherResult assume(final String key, boolean expectedResult) { return assume(key, expectedResult, null); } @@ -117,20 +114,20 @@ public static CriteriaResponse assume(final String key, boolean expectedResult) * @param key name of the key that you want to change the result * @param metadata additional information about the assumption (JSON) * @param expectedResult that will be returned when performing isItOn - * @return CriteriaResponse with the manipulated result + * @return SwitcherResult with the manipulated result */ - public static CriteriaResponse assume(final String key, boolean expectedResult, String metadata) { - CriteriaResponse criteriaResponse = new CriteriaResponse(); - criteriaResponse.setResult(expectedResult); - criteriaResponse.setReason("Switcher bypassed"); + public static SwitcherResult assume(final String key, boolean expectedResult, String metadata) { + SwitcherResult switcherResult = new SwitcherResult(); + switcherResult.setResult(expectedResult); + switcherResult.setReason("Switcher bypassed"); if (StringUtils.isNotBlank(metadata)) { Gson gson = new Gson(); - criteriaResponse.setMetadata(gson.fromJson(metadata, Object.class)); + switcherResult.setMetadata(gson.fromJson(metadata, Object.class)); } - bypass.put(key, criteriaResponse); - return criteriaResponse; + bypass.put(key, switcherResult); + return switcherResult; } /** @@ -142,7 +139,7 @@ public static void forget(final String key) { bypass.remove(key); } - public static Map getBypass() { + public static Map getBypass() { return bypass; } diff --git a/src/main/java/com/github/switcherapi/client/model/AsyncSwitcher.java b/src/main/java/com/github/switcherapi/client/model/AsyncSwitcher.java index d9c98975..b8fb8bfb 100644 --- a/src/main/java/com/github/switcherapi/client/model/AsyncSwitcher.java +++ b/src/main/java/com/github/switcherapi/client/model/AsyncSwitcher.java @@ -1,7 +1,6 @@ package com.github.switcherapi.client.model; import com.github.switcherapi.client.exception.SwitcherException; -import com.github.switcherapi.client.model.response.CriteriaResponse; import com.github.switcherapi.client.utils.SwitcherUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,19 +18,19 @@ * @since 2021-11-27 * */ -public class AsyncSwitcher { +public class AsyncSwitcher { private static final Logger logger = LoggerFactory.getLogger(AsyncSwitcher.class); private final ExecutorService executorService; - private final SwitcherInterface switcherInterface; + private final SwitcherInterface switcherInterface; private final long delay; private long nextRun = 0; - public AsyncSwitcher(final SwitcherInterface switcherInterface, long delay) { + public AsyncSwitcher(final SwitcherInterface switcherInterface, long delay) { this.executorService = Executors.newCachedThreadPool(r -> { Thread thread = new Thread(r); thread.setName(SWITCHER_ASYNC_WORKER.toString()); @@ -60,7 +59,7 @@ public synchronized void execute() { public void run() { try { - final CriteriaResponse response = switcherInterface.executeCriteria(); + final SwitcherResult response = switcherInterface.executeCriteria(); switcherInterface.updateHistoryExecution(response); } catch (SwitcherException e) { logger.error(e.getMessage(), e); diff --git a/src/main/java/com/github/switcherapi/client/model/Switcher.java b/src/main/java/com/github/switcherapi/client/model/Switcher.java index dce49576..ba6abb3f 100644 --- a/src/main/java/com/github/switcherapi/client/model/Switcher.java +++ b/src/main/java/com/github/switcherapi/client/model/Switcher.java @@ -3,7 +3,6 @@ import com.github.switcherapi.client.SwitcherContext; import com.github.switcherapi.client.SwitcherExecutor; import com.github.switcherapi.client.exception.SwitcherException; -import com.github.switcherapi.client.model.response.CriteriaResponse; import java.util.*; @@ -24,12 +23,14 @@ public final class Switcher extends SwitcherBuilder { public static final String SHOW_REASON = "showReason"; public static final String BYPASS_METRIC = "bypassMetric"; + + private final SwitcherExecutor context; private final String switcherKey; - private final Set historyExecution; + private final Set historyExecution; - private AsyncSwitcher asyncSwitcher; + private AsyncSwitcher asyncSwitcher; /** * Use {@link SwitcherContext#getSwitcher(String)} to create this object. @@ -38,7 +39,8 @@ public final class Switcher extends SwitcherBuilder { * @param context client context in which the switcher will be executed (local/remote) */ public Switcher(final String switcherKey, final SwitcherExecutor context) { - super(context); + super(context.getSwitcherProperties()); + this.context = context; this.switcherKey = switcherKey; this.historyExecution = new HashSet<>(); this.entry = new ArrayList<>(); @@ -75,40 +77,40 @@ public Switcher prepareEntry(final Entry entry) { @Override public boolean isItOn() throws SwitcherException { - final CriteriaResponse response = submit(); + final SwitcherResult response = submit(); return response.isItOn(); } @Override - public CriteriaResponse submit() throws SwitcherException { + public SwitcherResult submit() throws SwitcherException { if (SwitcherExecutor.getBypass().containsKey(switcherKey)) { return SwitcherExecutor.getBypass().get(switcherKey).buildFromSwitcher(this); } if (canUseAsync()) { - if (asyncSwitcher == null) { - asyncSwitcher = new AsyncSwitcher(this, super.delay); + if (Objects.isNull(asyncSwitcher)) { + asyncSwitcher = new AsyncSwitcher<>(this, super.delay); } asyncSwitcher.execute(); - final Optional response = getFromHistory(); + final Optional response = getFromHistory(); if (response.isPresent()) { return response.get(); } } - final CriteriaResponse response = this.context.executeCriteria(this); + final SwitcherResult response = this.context.executeCriteria(this); this.updateHistoryExecution(response); return response; } @Override - public CriteriaResponse executeCriteria() { + public SwitcherResult executeCriteria() { return this.context.executeCriteria(this); } @Override - public void updateHistoryExecution(final CriteriaResponse response) { + public void updateHistoryExecution(final SwitcherResult response) { this.historyExecution.removeIf(item -> this.switcherKey.equals(item.getSwitcherKey()) && this.entry.equals(item.getEntry())); @@ -124,17 +126,6 @@ public String getSwitcherKey() { public List getEntry() { return this.entry; } - - /** - * This method builds up the request made by the client to reach the Switcher API. - * - * @return json input request - */ - public GsonInputRequest getInputRequest() { - return new GsonInputRequest( - this.entry != null ? - this.entry.toArray(new Entry[0]) : null); - } public boolean isBypassMetrics() { return bypassMetrics; @@ -148,10 +139,10 @@ private boolean canUseAsync() { return super.delay > 0 && !this.historyExecution.isEmpty(); } - private Optional getFromHistory() { - for (CriteriaResponse criteriaResponse : historyExecution) { - if (criteriaResponse.getEntry().equals(getEntry())) { - return Optional.of(criteriaResponse); + private Optional getFromHistory() { + for (SwitcherResult switcherResult : historyExecution) { + if (switcherResult.getEntry().equals(getEntry())) { + return Optional.of(switcherResult); } } return Optional.empty(); @@ -162,18 +153,5 @@ public String toString() { return String.format("Switcher [switcherKey= %s, entry= %s, bypassMetrics= %s]", switcherKey, entry, bypassMetrics); } - - public static class GsonInputRequest { - - private final Entry[] entry; - - public GsonInputRequest(final Entry[] entry) { - this.entry = entry; - } - - public Entry[] getEntry() { - return this.entry; - } - } } diff --git a/src/main/java/com/github/switcherapi/client/model/SwitcherBuilder.java b/src/main/java/com/github/switcherapi/client/model/SwitcherBuilder.java index 49884f51..5ac96c94 100644 --- a/src/main/java/com/github/switcherapi/client/model/SwitcherBuilder.java +++ b/src/main/java/com/github/switcherapi/client/model/SwitcherBuilder.java @@ -1,6 +1,6 @@ package com.github.switcherapi.client.model; -import com.github.switcherapi.client.SwitcherExecutor; +import com.github.switcherapi.client.SwitcherProperties; import com.github.switcherapi.client.exception.SwitcherContextException; import org.apache.commons.lang3.StringUtils; @@ -13,9 +13,9 @@ * * @author Roger Floriano (petruki) */ -public abstract class SwitcherBuilder implements SwitcherInterface { +public abstract class SwitcherBuilder implements SwitcherInterface { - protected final SwitcherExecutor context; + protected final SwitcherProperties properties; protected long delay; @@ -26,9 +26,9 @@ public abstract class SwitcherBuilder implements SwitcherInterface { protected String defaultResult; protected List entry; - - protected SwitcherBuilder(final SwitcherExecutor context) { - this.context = context; + + protected SwitcherBuilder(final SwitcherProperties properties) { + this.properties = properties; this.entry = new ArrayList<>(); this.delay = 0; } @@ -53,7 +53,7 @@ public SwitcherBuilder throttle(long delay) { * @throws SwitcherContextException if Switcher is not configured to run locally using local mode */ public SwitcherBuilder remote(boolean remote) { - if (!this.context.isLocalEnabled()) { + if (!this.properties.getBoolean(ContextKey.LOCAL_MODE)) { throw new SwitcherContextException("Switcher is not configured to run locally"); } @@ -175,7 +175,4 @@ public String getDefaultResult() { return defaultResult; } - public SwitcherExecutor getContext() { - return context; - } } diff --git a/src/main/java/com/github/switcherapi/client/model/SwitcherInterface.java b/src/main/java/com/github/switcherapi/client/model/SwitcherInterface.java index b098522e..b021c7b5 100644 --- a/src/main/java/com/github/switcherapi/client/model/SwitcherInterface.java +++ b/src/main/java/com/github/switcherapi/client/model/SwitcherInterface.java @@ -2,7 +2,6 @@ import com.github.switcherapi.client.SwitcherContext; import com.github.switcherapi.client.exception.SwitcherException; -import com.github.switcherapi.client.model.response.CriteriaResponse; import java.util.List; @@ -15,7 +14,7 @@ *
  • Switcher get input/output
  • * */ -public interface SwitcherInterface { +public interface SwitcherInterface { /** * This method builds the Switcher object.
    @@ -31,39 +30,40 @@ public interface SwitcherInterface { * .build(); * * - * @return {@link Switcher} + * @return instance of SwitcherInterface + * @see Switcher */ - Switcher build(); + T build(); /** * Prepare the Switcher including a list of inputs necessary to run the criteria afterward. * * @param entry input object - * @return {@link Switcher} + * @return instance of SwitcherInterface */ - Switcher prepareEntry(final List entry); + T prepareEntry(final List entry); /** * Prepare the Switcher including a list of inputs necessary to run the criteria afterward. * * @param entry input object * @param add if false, the list will be cleaned and the entry provided will be the only input for this Switcher. - * @return {@link Switcher} + * @return instance of SwitcherInterface */ - Switcher prepareEntry(final Entry entry, final boolean add); + T prepareEntry(final Entry entry, final boolean add); /** * It adds an input to the list of inputs. *
    Under the table it calls {@link #prepareEntry(Entry, boolean)} passing true to the second argument. * * @param entry input object - * @return {@link Switcher} + * @return instance of SwitcherInterface */ - Switcher prepareEntry(final Entry entry); + T prepareEntry(final Entry entry); /** * Execute criteria based on a given switcher key provided via {@link SwitcherContext#getSwitcher(String)}. - *
    The detailed result is available in list of {@link CriteriaResponse}. + *
    The detailed result is available in list of {@link SwitcherResult}. * * @return criteria result * @throws SwitcherException connectivity or criteria errors regarding reading malformed snapshots @@ -72,26 +72,26 @@ public interface SwitcherInterface { /** * Execute criteria based on a given switcher key provided via {@link SwitcherContext#getSwitcher(String)}. - *
    The detailed result is available in list of {@link CriteriaResponse}. + *
    The detailed result is available in list of {@link SwitcherResult}. * - * @return {@link CriteriaResponse} + * @return {@link SwitcherResult} * @throws SwitcherException connectivity or criteria errors regarding reading malformed snapshots */ - CriteriaResponse submit() throws SwitcherException; + SwitcherResult submit() throws SwitcherException; /** * Execute the criteria evaluation. * - * @return the criteria response + * @return the switcher result */ - CriteriaResponse executeCriteria(); + SwitcherResult executeCriteria(); /** * Update the history of executions. * * @param response the response to be updated */ - void updateHistoryExecution(CriteriaResponse response); + void updateHistoryExecution(SwitcherResult response); /** * Get the key of the switcher. diff --git a/src/main/java/com/github/switcherapi/client/model/response/CriteriaResponse.java b/src/main/java/com/github/switcherapi/client/model/SwitcherResult.java similarity index 61% rename from src/main/java/com/github/switcherapi/client/model/response/CriteriaResponse.java rename to src/main/java/com/github/switcherapi/client/model/SwitcherResult.java index 9d99d2ad..8435650b 100644 --- a/src/main/java/com/github/switcherapi/client/model/response/CriteriaResponse.java +++ b/src/main/java/com/github/switcherapi/client/model/SwitcherResult.java @@ -1,20 +1,18 @@ -package com.github.switcherapi.client.model.response; +package com.github.switcherapi.client.model; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; -import com.github.switcherapi.client.model.Entry; -import com.github.switcherapi.client.model.StrategyValidator; -import com.github.switcherapi.client.model.Switcher; +import com.github.switcherapi.client.remote.dto.CriteriaResponse; import com.google.gson.Gson; /** * @author Roger Floriano (petruki) * @since 2019-12-24 */ -public class CriteriaResponse { +public class SwitcherResult { private static final String DEFAULT_REASON = "Default result"; @@ -32,11 +30,11 @@ public class CriteriaResponse { protected Map> entryWhen; - public CriteriaResponse() { + public SwitcherResult() { entryWhen = new HashMap<>(); } - public CriteriaResponse(final boolean result, final String reason, final Switcher switcher) { + private SwitcherResult(final boolean result, final String reason, final Switcher switcher) { this(); this.result = result; this.reason = reason; @@ -44,14 +42,14 @@ public CriteriaResponse(final boolean result, final String reason, final Switche this.entry = switcher.getEntry(); } - public CriteriaResponse buildFromSwitcher(Switcher switcher) { + public SwitcherResult buildFromSwitcher(Switcher switcher) { this.switcherKey = switcher.getSwitcherKey(); this.entry = switcher.getEntry(); if (Objects.nonNull(entry)) { for (Entry inputEntry : entry) { if (!isEntryMatching(inputEntry)) { - return new CriteriaResponse(!this.result, this.reason, switcher); + return new SwitcherResult(!this.result, this.reason, switcher); } } } @@ -64,16 +62,26 @@ private boolean isEntryMatching(Entry inputEntry) { entryWhen.get(inputEntry.getStrategy()).contains(inputEntry.getInput()); } - public static CriteriaResponse buildFromDefault(Switcher switcher) { - return new CriteriaResponse(Boolean.parseBoolean(switcher.getDefaultResult()), DEFAULT_REASON, switcher); + public static SwitcherResult buildFromDefault(Switcher switcher) { + return new SwitcherResult(Boolean.parseBoolean(switcher.getDefaultResult()), DEFAULT_REASON, switcher); } - public static CriteriaResponse buildResultFail(String reason, Switcher switcher) { - return new CriteriaResponse(Boolean.FALSE, reason, switcher); + public static SwitcherResult buildResultFail(String reason, Switcher switcher) { + return new SwitcherResult(Boolean.FALSE, reason, switcher); } - public static CriteriaResponse buildResultSuccess(Switcher switcher) { - return new CriteriaResponse(Boolean.TRUE, DEFAULT_SUCCESS, switcher); + public static SwitcherResult buildResultSuccess(Switcher switcher) { + return new SwitcherResult(Boolean.TRUE, DEFAULT_SUCCESS, switcher); + } + + public static SwitcherResult buildResultFromRemote(CriteriaResponse criteriaResponse) { + SwitcherResult switcherResult = new SwitcherResult(); + switcherResult.setSwitcherKey(criteriaResponse.getSwitcherKey()); + switcherResult.setResult(criteriaResponse.getResult()); + switcherResult.setReason(criteriaResponse.getReason()); + switcherResult.setMetadata(criteriaResponse.getMetadata()); + switcherResult.setEntry(criteriaResponse.getEntry()); + return switcherResult; } public boolean isItOn() { @@ -117,11 +125,11 @@ public void setEntry(List entry) { this.entry = entry; } - public CriteriaResponse when(StrategyValidator strategy, String input) { + public SwitcherResult when(StrategyValidator strategy, String input) { return when(strategy, List.of(input)); } - public CriteriaResponse when(StrategyValidator strategy, List inputs) { + public SwitcherResult when(StrategyValidator strategy, List inputs) { entryWhen.put(strategy.toString(), inputs); return this; } @@ -140,7 +148,7 @@ public boolean equals(Object obj) { if (getClass() != obj.getClass()) return false; - final CriteriaResponse other = (CriteriaResponse) obj; + final SwitcherResult other = (SwitcherResult) obj; return Objects.equals(entry, other.entry) && result == other.result && Objects.equals(switcherKey, other.switcherKey); @@ -148,7 +156,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return "CriteriaResponse [result=" + result + + return "SwitcherResult [result=" + result + ", reason=" + reason + ", metadata=" + metadata + ", switcherKey=" + switcherKey + diff --git a/src/main/java/com/github/switcherapi/client/model/criteria/Criteria.java b/src/main/java/com/github/switcherapi/client/model/criteria/Data.java similarity index 91% rename from src/main/java/com/github/switcherapi/client/model/criteria/Criteria.java rename to src/main/java/com/github/switcherapi/client/model/criteria/Data.java index ba0aeec6..d1f8d47b 100644 --- a/src/main/java/com/github/switcherapi/client/model/criteria/Criteria.java +++ b/src/main/java/com/github/switcherapi/client/model/criteria/Data.java @@ -4,7 +4,7 @@ * @author Roger Floriano (petruki) * @since 2019-12-24 */ -public class Criteria { +public class Data { private Domain domain; diff --git a/src/main/java/com/github/switcherapi/client/model/criteria/Snapshot.java b/src/main/java/com/github/switcherapi/client/model/criteria/Snapshot.java index 81e3663f..62dcd3e0 100644 --- a/src/main/java/com/github/switcherapi/client/model/criteria/Snapshot.java +++ b/src/main/java/com/github/switcherapi/client/model/criteria/Snapshot.java @@ -7,17 +7,17 @@ */ public class Snapshot { - private Criteria data; + private Data data; public Domain getDomain() { return data != null ? data.getDomain() : new Domain(); } - public Criteria getData() { + public Data getData() { return data; } - public void setData(Criteria data) { + public void setData(Data data) { this.data = data; } diff --git a/src/main/java/com/github/switcherapi/client/remote/ClientWS.java b/src/main/java/com/github/switcherapi/client/remote/ClientWS.java index 8987b2bc..4a667bb0 100644 --- a/src/main/java/com/github/switcherapi/client/remote/ClientWS.java +++ b/src/main/java/com/github/switcherapi/client/remote/ClientWS.java @@ -1,15 +1,12 @@ package com.github.switcherapi.client.remote; +import com.github.switcherapi.client.model.criteria.Snapshot; +import com.github.switcherapi.client.remote.dto.SwitchersCheck; +import com.github.switcherapi.client.remote.dto.*; + import java.util.Optional; import java.util.Set; -import com.github.switcherapi.client.model.Switcher; -import com.github.switcherapi.client.model.criteria.Snapshot; -import com.github.switcherapi.client.model.criteria.SwitchersCheck; -import com.github.switcherapi.client.model.response.AuthResponse; -import com.github.switcherapi.client.model.response.CriteriaResponse; -import com.github.switcherapi.client.model.response.SnapshotVersionResponse; - /** * @author Roger Floriano {petruki) * @since 2019-12-24 @@ -49,11 +46,11 @@ public interface ClientWS { /** * Returns the verification configured for a specific switcher (key) * - * @param switcher store all necessary input to access the criteria + * @param criteriaRequest Criteria request * @param token Access token * @return the execution based on the configured switcher */ - CriteriaResponse executeCriteria(final Switcher switcher, final String token); + CriteriaResponse executeCriteria(final CriteriaRequest criteriaRequest, final String token); /** * Returns the token to access all available endpoints diff --git a/src/main/java/com/github/switcherapi/client/remote/ClientWSImpl.java b/src/main/java/com/github/switcherapi/client/remote/ClientWSImpl.java index 91df9933..661010ab 100644 --- a/src/main/java/com/github/switcherapi/client/remote/ClientWSImpl.java +++ b/src/main/java/com/github/switcherapi/client/remote/ClientWSImpl.java @@ -5,11 +5,8 @@ import com.github.switcherapi.client.model.ContextKey; import com.github.switcherapi.client.model.Switcher; import com.github.switcherapi.client.model.criteria.Snapshot; -import com.github.switcherapi.client.model.criteria.SwitchersCheck; -import com.github.switcherapi.client.model.response.AuthRequest; -import com.github.switcherapi.client.model.response.AuthResponse; -import com.github.switcherapi.client.model.response.CriteriaResponse; -import com.github.switcherapi.client.model.response.SnapshotVersionResponse; +import com.github.switcherapi.client.remote.dto.SwitchersCheck; +import com.github.switcherapi.client.remote.dto.*; import com.google.gson.Gson; import java.net.URI; @@ -52,22 +49,22 @@ public static ClientWS build(SwitcherProperties switcherProperties, ExecutorServ } @Override - public CriteriaResponse executeCriteria(final Switcher switcher, final String token) { + public CriteriaResponse executeCriteria(final CriteriaRequest criteriaRequest, final String token) { final String url = switcherProperties.getValue(ContextKey.URL); try { final URI uri = new URI(url) .resolve(String.format(CRITERIA_URL, url, - Switcher.KEY, switcher.getSwitcherKey(), + Switcher.KEY, criteriaRequest.getSwitcherKey(), Switcher.SHOW_REASON, Boolean.TRUE, - Switcher.BYPASS_METRIC, switcher.isBypassMetrics())); + Switcher.BYPASS_METRIC, criteriaRequest.isBypassMetric())); final HttpResponse response = client.send(HttpRequest.newBuilder() .uri(uri) .headers(HEADER_AUTHORIZATION, String.format(TOKEN_TEXT, token), CONTENT_TYPE[0], CONTENT_TYPE[1]) .timeout(Duration.ofMillis(timeoutMs)) - .POST(HttpRequest.BodyPublishers.ofString(gson.toJson(switcher.getInputRequest()))) + .POST(HttpRequest.BodyPublishers.ofString(gson.toJson(criteriaRequest.getInputRequest()))) .build(), HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { @@ -75,8 +72,8 @@ public CriteriaResponse executeCriteria(final Switcher switcher, final String to } final CriteriaResponse criteriaResponse = gson.fromJson(response.body(), CriteriaResponse.class); - criteriaResponse.setSwitcherKey(switcher.getSwitcherKey()); - criteriaResponse.setEntry(switcher.getEntry()); + criteriaResponse.setSwitcherKey(criteriaRequest.getSwitcherKey()); + criteriaResponse.setEntry(criteriaRequest.getEntry()); return criteriaResponse; } catch (Exception e) { return exceptionHandler(e, url); diff --git a/src/main/java/com/github/switcherapi/client/model/response/AuthRequest.java b/src/main/java/com/github/switcherapi/client/remote/dto/AuthRequest.java similarity index 93% rename from src/main/java/com/github/switcherapi/client/model/response/AuthRequest.java rename to src/main/java/com/github/switcherapi/client/remote/dto/AuthRequest.java index 4ae46439..63f86f75 100644 --- a/src/main/java/com/github/switcherapi/client/model/response/AuthRequest.java +++ b/src/main/java/com/github/switcherapi/client/remote/dto/AuthRequest.java @@ -1,4 +1,4 @@ -package com.github.switcherapi.client.model.response; +package com.github.switcherapi.client.remote.dto; /** * @author Roger Floriano (petruki) diff --git a/src/main/java/com/github/switcherapi/client/model/response/AuthResponse.java b/src/main/java/com/github/switcherapi/client/remote/dto/AuthResponse.java similarity index 88% rename from src/main/java/com/github/switcherapi/client/model/response/AuthResponse.java rename to src/main/java/com/github/switcherapi/client/remote/dto/AuthResponse.java index d9c97c3c..c9031ea8 100644 --- a/src/main/java/com/github/switcherapi/client/model/response/AuthResponse.java +++ b/src/main/java/com/github/switcherapi/client/remote/dto/AuthResponse.java @@ -1,4 +1,4 @@ -package com.github.switcherapi.client.model.response; +package com.github.switcherapi.client.remote.dto; /** * @author Roger Floriano (petruki) diff --git a/src/main/java/com/github/switcherapi/client/remote/dto/CriteriaRequest.java b/src/main/java/com/github/switcherapi/client/remote/dto/CriteriaRequest.java new file mode 100644 index 00000000..f9097683 --- /dev/null +++ b/src/main/java/com/github/switcherapi/client/remote/dto/CriteriaRequest.java @@ -0,0 +1,63 @@ +package com.github.switcherapi.client.remote.dto; + +import com.github.switcherapi.client.model.Entry; +import com.github.switcherapi.client.model.Switcher; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class CriteriaRequest { + + private String switcherKey; + + private List entry; + + private boolean bypassMetric; + + public static CriteriaRequest build(final Switcher switcher) { + final CriteriaRequest request = new CriteriaRequest(); + request.switcherKey = switcher.getSwitcherKey(); + request.entry = switcher.getEntry(); + request.bypassMetric = switcher.isBypassMetrics(); + return request; + } + + public String getSwitcherKey() { + return switcherKey; + } + + public List getEntry() { + return entry; + } + + public boolean isBypassMetric() { + return bypassMetric; + } + + /** + * This method builds up the request made by the client to reach the Switcher API. + * + * @return json input request + */ + public CriteriaRequest.GsonInputRequest getInputRequest() { + return new CriteriaRequest.GsonInputRequest( + Optional.ofNullable(this.entry) + .orElseGet(ArrayList::new) + .toArray(new Entry[0])); + } + + public static class GsonInputRequest { + + private final Entry[] entry; + + public GsonInputRequest(final Entry[] entry) { + this.entry = entry; + } + + public Entry[] getEntry() { + return this.entry; + } + } + +} diff --git a/src/main/java/com/github/switcherapi/client/remote/dto/CriteriaResponse.java b/src/main/java/com/github/switcherapi/client/remote/dto/CriteriaResponse.java new file mode 100644 index 00000000..f1b0ddc1 --- /dev/null +++ b/src/main/java/com/github/switcherapi/client/remote/dto/CriteriaResponse.java @@ -0,0 +1,59 @@ +package com.github.switcherapi.client.remote.dto; + +import com.github.switcherapi.client.model.Entry; + +import java.util.List; + +public class CriteriaResponse { + + private boolean result; + + private String reason; + + private Object metadata; + + private String switcherKey; + + protected List entry; + + public boolean getResult() { + return result; + } + + public void setResult(boolean result) { + this.result = result; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public Object getMetadata() { + return metadata; + } + + public void setMetadata(Object metadata) { + this.metadata = metadata; + } + + public String getSwitcherKey() { + return switcherKey; + } + + public void setSwitcherKey(String switcherKey) { + this.switcherKey = switcherKey; + } + + public List getEntry() { + return entry; + } + + public void setEntry(List entry) { + this.entry = entry; + } + +} diff --git a/src/main/java/com/github/switcherapi/client/model/response/SnapshotVersionResponse.java b/src/main/java/com/github/switcherapi/client/remote/dto/SnapshotVersionResponse.java similarity index 82% rename from src/main/java/com/github/switcherapi/client/model/response/SnapshotVersionResponse.java rename to src/main/java/com/github/switcherapi/client/remote/dto/SnapshotVersionResponse.java index 8b7b6f6d..833e51c8 100644 --- a/src/main/java/com/github/switcherapi/client/model/response/SnapshotVersionResponse.java +++ b/src/main/java/com/github/switcherapi/client/remote/dto/SnapshotVersionResponse.java @@ -1,4 +1,4 @@ -package com.github.switcherapi.client.model.response; +package com.github.switcherapi.client.remote.dto; /** * @author Roger Floriano (petruki) diff --git a/src/main/java/com/github/switcherapi/client/model/criteria/SwitchersCheck.java b/src/main/java/com/github/switcherapi/client/remote/dto/SwitchersCheck.java similarity index 94% rename from src/main/java/com/github/switcherapi/client/model/criteria/SwitchersCheck.java rename to src/main/java/com/github/switcherapi/client/remote/dto/SwitchersCheck.java index 2a7a77ae..a43bd3bf 100644 --- a/src/main/java/com/github/switcherapi/client/model/criteria/SwitchersCheck.java +++ b/src/main/java/com/github/switcherapi/client/remote/dto/SwitchersCheck.java @@ -1,4 +1,4 @@ -package com.github.switcherapi.client.model.criteria; +package com.github.switcherapi.client.remote.dto; import java.util.Arrays; import java.util.Set; diff --git a/src/main/java/com/github/switcherapi/client/service/local/ClientLocal.java b/src/main/java/com/github/switcherapi/client/service/local/ClientLocal.java index cabcc403..44e76c57 100644 --- a/src/main/java/com/github/switcherapi/client/service/local/ClientLocal.java +++ b/src/main/java/com/github/switcherapi/client/service/local/ClientLocal.java @@ -3,7 +3,7 @@ import com.github.switcherapi.client.exception.SwitcherException; import com.github.switcherapi.client.model.Switcher; import com.github.switcherapi.client.model.criteria.Domain; -import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.model.SwitcherResult; import java.util.List; import java.util.Set; @@ -34,6 +34,6 @@ public interface ClientLocal { * @return The criteria result * @throws SwitcherException If encountered either invalid input or misconfiguration */ - CriteriaResponse executeCriteria(final Switcher switcher, final Domain domain); + SwitcherResult executeCriteria(final Switcher switcher, final Domain domain); } diff --git a/src/main/java/com/github/switcherapi/client/service/local/ClientLocalService.java b/src/main/java/com/github/switcherapi/client/service/local/ClientLocalService.java index 361244c9..98c2107a 100644 --- a/src/main/java/com/github/switcherapi/client/service/local/ClientLocalService.java +++ b/src/main/java/com/github/switcherapi/client/service/local/ClientLocalService.java @@ -8,7 +8,7 @@ import com.github.switcherapi.client.model.criteria.Domain; import com.github.switcherapi.client.model.criteria.Group; import com.github.switcherapi.client.model.criteria.Strategy; -import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.model.SwitcherResult; import com.github.switcherapi.client.service.SwitcherValidator; import com.github.switcherapi.client.utils.SwitcherUtils; import org.apache.commons.lang3.ArrayUtils; @@ -61,9 +61,9 @@ public List checkSwitchers(final Set switchers, final Domain dom } @Override - public CriteriaResponse executeCriteria(final Switcher switcher, final Domain domain) { + public SwitcherResult executeCriteria(final Switcher switcher, final Domain domain) { if (!domain.isActivated()) { - return CriteriaResponse.buildResultFail(DISABLED_DOMAIN, switcher); + return SwitcherResult.buildResultFail(DISABLED_DOMAIN, switcher); } Config config; @@ -71,27 +71,27 @@ public CriteriaResponse executeCriteria(final Switcher switcher, final Domain do config = findConfigInGroup(group, switcher.getSwitcherKey()); if (config != null) { - return getCriteriaResponse(switcher, group, config); + return getSwitcherResult(switcher, group, config); } } throw new SwitcherKeyNotFoundException(switcher.getSwitcherKey()); } - private CriteriaResponse getCriteriaResponse(Switcher switcher, Group group, Config config) { + private SwitcherResult getSwitcherResult(Switcher switcher, Group group, Config config) { if (!group.isActivated()) { - return CriteriaResponse.buildResultFail(DISABLED_GROUP, switcher); + return SwitcherResult.buildResultFail(DISABLED_GROUP, switcher); } if (!config.isActivated()) { - return CriteriaResponse.buildResultFail(DISABLED_CONFIG, switcher); + return SwitcherResult.buildResultFail(DISABLED_CONFIG, switcher); } if (ArrayUtils.isNotEmpty(config.getStrategies())) { return this.processOperation(config.getStrategies(), switcher.getEntry(), switcher); } - return CriteriaResponse.buildResultSuccess(switcher); + return SwitcherResult.buildResultSuccess(switcher); } private Config findConfigInGroup(final Group group, final String switcherKey) { @@ -106,11 +106,11 @@ private Config findConfigInGroup(final Group group, final String switcherKey) { * * @param configStrategies to be processed * @param input sent by the client - * @return CriteriaResponse containing the result of the execution + * @return SwitcherResult containing the result of the execution * @throws SwitcherException If encountered either invalid input or misconfiguration */ - private CriteriaResponse processOperation(final Strategy[] configStrategies, final List input, - final Switcher switcher) { + private SwitcherResult processOperation(final Strategy[] configStrategies, final List input, + final Switcher switcher) { SwitcherUtils.debug(logger, LOG_PROCESS_OP_TEMPLATE, Arrays.toString(configStrategies)); for (final Strategy strategy : configStrategies) { @@ -129,11 +129,11 @@ private CriteriaResponse processOperation(final Strategy[] configStrategies, fin } } - return CriteriaResponse.buildResultSuccess(switcher); + return SwitcherResult.buildResultSuccess(switcher); } - private CriteriaResponse strategyFailed(Switcher switcher, Strategy strategy, String pattern) { - return CriteriaResponse.buildResultFail(String.format(pattern, strategy.getStrategy()), switcher); + private SwitcherResult strategyFailed(Switcher switcher, Strategy strategy, String pattern) { + return SwitcherResult.buildResultFail(String.format(pattern, strategy.getStrategy()), switcher); } private Entry tryGetSwitcherInput(final List input, Strategy strategy) { diff --git a/src/main/java/com/github/switcherapi/client/service/local/SwitcherLocalService.java b/src/main/java/com/github/switcherapi/client/service/local/SwitcherLocalService.java index 8e98a52c..79f0b5b1 100644 --- a/src/main/java/com/github/switcherapi/client/service/local/SwitcherLocalService.java +++ b/src/main/java/com/github/switcherapi/client/service/local/SwitcherLocalService.java @@ -5,7 +5,8 @@ import com.github.switcherapi.client.exception.*; import com.github.switcherapi.client.model.ContextKey; import com.github.switcherapi.client.model.Switcher; -import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.remote.dto.CriteriaRequest; +import com.github.switcherapi.client.model.SwitcherResult; import com.github.switcherapi.client.service.remote.ClientRemote; import com.github.switcherapi.client.utils.SnapshotEventHandler; import com.github.switcherapi.client.utils.SnapshotLoader; @@ -99,13 +100,13 @@ public boolean notifyChange(final String snapshotFile) { } @Override - public CriteriaResponse executeCriteria(final Switcher switcher) { + public SwitcherResult executeCriteria(final Switcher switcher) { SwitcherUtils.debug(logger, "[Local] request: {}", switcher); - CriteriaResponse response; + SwitcherResult response; try { if (switcher.isRemote()) { - response = this.clientRemote.executeCriteria(switcher); + response = SwitcherResult.buildResultFromRemote(this.clientRemote.executeCriteria(CriteriaRequest.build(switcher))); SwitcherUtils.debug(logger, "[Remote] response: {}", response); } else { response = this.clientLocal.executeCriteria(switcher, this.domain); @@ -116,7 +117,7 @@ public CriteriaResponse executeCriteria(final Switcher switcher) { throw e; } - response = CriteriaResponse.buildFromDefault(switcher); + response = SwitcherResult.buildFromDefault(switcher); SwitcherUtils.debug(logger, "[Default] response: {}", response); } diff --git a/src/main/java/com/github/switcherapi/client/service/remote/ClientRemote.java b/src/main/java/com/github/switcherapi/client/service/remote/ClientRemote.java index 9bc71dcf..82707c6c 100644 --- a/src/main/java/com/github/switcherapi/client/service/remote/ClientRemote.java +++ b/src/main/java/com/github/switcherapi/client/service/remote/ClientRemote.java @@ -1,10 +1,10 @@ package com.github.switcherapi.client.service.remote; import com.github.switcherapi.client.exception.SwitcherException; -import com.github.switcherapi.client.model.Switcher; import com.github.switcherapi.client.model.criteria.Snapshot; -import com.github.switcherapi.client.model.criteria.SwitchersCheck; -import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.remote.dto.SwitchersCheck; +import com.github.switcherapi.client.remote.dto.CriteriaRequest; +import com.github.switcherapi.client.remote.dto.CriteriaResponse; import java.util.Set; @@ -19,11 +19,11 @@ public interface ClientRemote { * validating from the top of the node (Domain) ascending to the lower level * (Strategy) * - * @param switcher Configuration switcher to be validated + * @param criteriaRequest Criteria request * @return The criteria result * @throws SwitcherException If encountered either invalid input or misconfiguration */ - CriteriaResponse executeCriteria(final Switcher switcher); + CriteriaResponse executeCriteria(final CriteriaRequest criteriaRequest); /** * Resolve the snapshot from the remote server diff --git a/src/main/java/com/github/switcherapi/client/service/remote/ClientRemoteService.java b/src/main/java/com/github/switcherapi/client/service/remote/ClientRemoteService.java index 52b8c901..f6c1cadc 100644 --- a/src/main/java/com/github/switcherapi/client/service/remote/ClientRemoteService.java +++ b/src/main/java/com/github/switcherapi/client/service/remote/ClientRemoteService.java @@ -5,12 +5,9 @@ import com.github.switcherapi.client.exception.SwitcherInvalidDateTimeArgumentException; import com.github.switcherapi.client.exception.SwitcherRemoteException; import com.github.switcherapi.client.model.ContextKey; -import com.github.switcherapi.client.model.Switcher; import com.github.switcherapi.client.model.criteria.Snapshot; -import com.github.switcherapi.client.model.criteria.SwitchersCheck; -import com.github.switcherapi.client.model.response.AuthResponse; -import com.github.switcherapi.client.model.response.CriteriaResponse; -import com.github.switcherapi.client.model.response.SnapshotVersionResponse; +import com.github.switcherapi.client.remote.dto.SwitchersCheck; +import com.github.switcherapi.client.remote.dto.*; import com.github.switcherapi.client.remote.ClientWS; import com.github.switcherapi.client.utils.SwitcherUtils; import org.apache.commons.lang3.StringUtils; @@ -41,13 +38,13 @@ public ClientRemoteService(ClientWS clientWs, SwitcherProperties switcherPropert } @Override - public CriteriaResponse executeCriteria(final Switcher switcher) { + public CriteriaResponse executeCriteria(final CriteriaRequest criteriaRequest) { final TokenStatus tokenStatus = this.isTokenValid(); try { this.auth(tokenStatus); - return this.clientWs.executeCriteria(switcher, + return this.clientWs.executeCriteria(criteriaRequest, Optional.of(this.authResponse).orElseGet(AuthResponse::new).getToken()); } catch (final SwitcherRemoteException e) { if (tokenStatus != TokenStatus.SILENT) { diff --git a/src/main/java/com/github/switcherapi/client/service/remote/SwitcherRemoteService.java b/src/main/java/com/github/switcherapi/client/service/remote/SwitcherRemoteService.java index a4282281..2323945f 100644 --- a/src/main/java/com/github/switcherapi/client/service/remote/SwitcherRemoteService.java +++ b/src/main/java/com/github/switcherapi/client/service/remote/SwitcherRemoteService.java @@ -5,8 +5,10 @@ import com.github.switcherapi.client.exception.SwitchersValidationException; import com.github.switcherapi.client.model.ContextKey; import com.github.switcherapi.client.model.Switcher; -import com.github.switcherapi.client.model.criteria.SwitchersCheck; -import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.remote.dto.SwitchersCheck; +import com.github.switcherapi.client.remote.dto.CriteriaRequest; +import com.github.switcherapi.client.model.SwitcherResult; +import com.github.switcherapi.client.remote.dto.CriteriaResponse; import com.github.switcherapi.client.utils.SwitcherUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -34,31 +36,31 @@ public SwitcherRemoteService(ClientRemote clientRemote, SwitcherExecutor switche } @Override - public CriteriaResponse executeCriteria(final Switcher switcher) { + public SwitcherResult executeCriteria(final Switcher switcher) { SwitcherUtils.debug(logger, "[Remote] request: {}", switcher); try { - final CriteriaResponse response = this.clientRemote.executeCriteria(switcher); + final CriteriaResponse response = this.clientRemote.executeCriteria(CriteriaRequest.build(switcher)); SwitcherUtils.debug(logger, "[Remote] response: {}", response); - return response; + return SwitcherResult.buildResultFromRemote(response); } catch (final SwitcherRemoteException e) { logger.error("Failed to execute criteria - Cause: {}", e.getMessage(), e.getCause()); return tryExecuteLocalCriteria(switcher, e); } } - private CriteriaResponse tryExecuteLocalCriteria(final Switcher switcher, - final SwitcherRemoteException e) { + private SwitcherResult tryExecuteLocalCriteria(final Switcher switcher, + final SwitcherRemoteException e) { if (StringUtils.isNotBlank(switcherProperties.getValue(ContextKey.SILENT_MODE))) { - final CriteriaResponse response = this.switcherLocal.executeCriteria(switcher); + final SwitcherResult response = this.switcherLocal.executeCriteria(switcher); SwitcherUtils.debug(logger, "[Silent] response: {}", response); return response; } if (StringUtils.isNotBlank(switcher.getDefaultResult())) { - final CriteriaResponse response = CriteriaResponse.buildFromDefault(switcher); + final SwitcherResult response = SwitcherResult.buildFromDefault(switcher); SwitcherUtils.debug(logger, "[Default] response: {}", response); return response; diff --git a/src/main/java/com/github/switcherapi/client/test/SwitcherTestExtension.java b/src/main/java/com/github/switcherapi/client/test/SwitcherTestExtension.java index 04dc6a06..0abbdfaf 100644 --- a/src/main/java/com/github/switcherapi/client/test/SwitcherTestExtension.java +++ b/src/main/java/com/github/switcherapi/client/test/SwitcherTestExtension.java @@ -1,7 +1,7 @@ package com.github.switcherapi.client.test; import com.github.switcherapi.client.SwitcherExecutor; -import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.model.SwitcherResult; import org.apache.commons.lang3.ArrayUtils; import org.junit.jupiter.api.extension.*; import org.junit.jupiter.api.extension.ExtensionContext.Namespace; @@ -79,22 +79,22 @@ private void mockMultipleSwitchers(ExtensionContext context, SwitcherTest switch .toArray(String[]::new); for (SwitcherTestValue value : switcherTest.switchers()) { - CriteriaResponse criteriaResponse = SwitcherExecutor.assume(value.key(), inverted != value.result(), value.metadata()); - applySwitcherTestWhen(criteriaResponse, value.when()); + SwitcherResult switcherResult = SwitcherExecutor.assume(value.key(), inverted != value.result(), value.metadata()); + applySwitcherTestWhen(switcherResult, value.when()); } getStore(context).put(STORE_KEYS, keys); } private void mockSingleSwitcher(ExtensionContext context, SwitcherTest switcherTest, boolean inverted) { - CriteriaResponse criteriaResponse = SwitcherExecutor.assume(switcherTest.key(), inverted != switcherTest.result(), switcherTest.metadata()); - applySwitcherTestWhen(criteriaResponse, switcherTest.when()); + SwitcherResult switcherResult = SwitcherExecutor.assume(switcherTest.key(), inverted != switcherTest.result(), switcherTest.metadata()); + applySwitcherTestWhen(switcherResult, switcherTest.when()); getStore(context).put(STORE_KEY, switcherTest.key()); } - private void applySwitcherTestWhen(CriteriaResponse criteriaResponse, SwitcherTestWhen[] whens) { + private void applySwitcherTestWhen(SwitcherResult switcherResult, SwitcherTestWhen[] whens) { for (SwitcherTestWhen when : whens) { - criteriaResponse.when(when.strategy(), Arrays.asList(when.input())); + switcherResult.when(when.strategy(), Arrays.asList(when.input())); } } diff --git a/src/main/java/com/github/switcherapi/client/utils/SnapshotLoader.java b/src/main/java/com/github/switcherapi/client/utils/SnapshotLoader.java index 0b24cd2d..8312abe4 100644 --- a/src/main/java/com/github/switcherapi/client/utils/SnapshotLoader.java +++ b/src/main/java/com/github/switcherapi/client/utils/SnapshotLoader.java @@ -13,6 +13,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Objects; /** * @author Roger Floriano (petruki) @@ -53,11 +54,42 @@ public static Domain loadSnapshot(final String snapshotFile) throws SwitcherSnap */ public static Domain loadSnapshot(final String snapshotLocation, final String environment) throws SwitcherSnapshotLoadException, IOException { - try (FileReader fileReader = new FileReader(String.format(SNAPSHOT_FILE_FORMAT, snapshotLocation, environment))) { + final String path = String.format(SNAPSHOT_FILE_FORMAT, snapshotLocation, environment); + + try (FileReader fileReader = new FileReader(path)) { final Snapshot data = gson.fromJson(fileReader, Snapshot.class); return data.getDomain(); } catch (JsonSyntaxException | JsonIOException e) { throw new SwitcherSnapshotLoadException(String.format(SNAPSHOT_FILE_FORMAT, snapshotLocation, environment), e); + } catch (FileNotFoundException e) { + return loadSnapshotFromResources(snapshotLocation, environment); + } + } + + /** + * Load snapshot from the resources folder + * + * @param snapshotLocation Snapshot folder + * @param environment name that is represented as [environment].json + * @return Serialized Domain object + * @throws SwitcherSnapshotLoadException when JSON file has errors + * @throws IOException when failing to read JSON file + */ + private static Domain loadSnapshotFromResources(final String snapshotLocation, final String environment) + throws SwitcherSnapshotLoadException, IOException { + final String path = String.format(SNAPSHOT_FILE_FORMAT, snapshotLocation, environment); + + try (InputStream is = SnapshotLoader.class.getResourceAsStream(path)) { + if (Objects.isNull(is)) { + throw new FileNotFoundException(path); + } + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { + final Snapshot data = gson.fromJson(reader, Snapshot.class); + return data.getDomain(); + } catch (JsonSyntaxException | JsonIOException e) { + throw new SwitcherSnapshotLoadException(String.format(SNAPSHOT_FILE_FORMAT, snapshotLocation, environment), e); + } } } diff --git a/src/main/java/com/github/switcherapi/client/utils/SwitcherUtils.java b/src/main/java/com/github/switcherapi/client/utils/SwitcherUtils.java index de9279cb..e4507b6b 100644 --- a/src/main/java/com/github/switcherapi/client/utils/SwitcherUtils.java +++ b/src/main/java/com/github/switcherapi/client/utils/SwitcherUtils.java @@ -10,11 +10,8 @@ import org.apache.commons.lang3.time.DateUtils; import org.slf4j.Logger; -import java.util.Date; +import java.util.*; import java.util.Map.Entry; -import java.util.Objects; -import java.util.Properties; -import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -26,7 +23,7 @@ public class SwitcherUtils { private static final String[] DURATION_UNIT = { "s", "m", "h", "d" }; private static final String ENV_VARIABLE_PATTERN = "\\$\\{(\\w+)}"; - private static final String ENV_DEFAULT_VARIABLE_PATTERN = "\\$\\{(\\w+):(.+)}"; + private static final String ENV_DEFAULT_VARIABLE_PATTERN = "\\$\\{(\\w+):(.+)?}"; private static final String PAYLOAD_PATTERN = "%s.%s"; private SwitcherUtils() {} @@ -101,12 +98,12 @@ public static String resolveProperties(String key, Properties prop) { return null; } - final StringBuilder sBuilder = resolveEnvironmentVariable(value); - if (sBuilder.toString().isEmpty()) { + final Object[] sBuilder = resolveEnvironmentVariable(value); + if (sBuilder[1].equals(Boolean.FALSE) && sBuilder[0].toString().isEmpty()) { return value; } - - return sBuilder.toString(); + + return sBuilder[0].toString(); } /** @@ -118,9 +115,7 @@ public static String resolveProperties(String key, Properties prop) { * @param args arguments to be replaced in the message */ public static void debug(Logger logger, String message, Object... args) { - if (logger.isDebugEnabled()) { - logger.debug(message, args); - } + logger.debug(message, args); } /** @@ -128,9 +123,9 @@ public static void debug(Logger logger, String message, Object... args) { * System environment or default argument. * * @param value assigned from the properties file - * @return Resolved value + * @return Array-pair: Resolved value and a boolean to indicate if it was resolved by var notation ${VAR:VALUE} */ - private static StringBuilder resolveEnvironmentVariable(final String value) { + private static Object[] resolveEnvironmentVariable(final String value) { Pattern pattern = Pattern.compile(ENV_VARIABLE_PATTERN); Matcher matcher = pattern.matcher(value); StringBuilder sBuilder = new StringBuilder(); @@ -143,11 +138,21 @@ private static StringBuilder resolveEnvironmentVariable(final String value) { pattern = Pattern.compile(ENV_DEFAULT_VARIABLE_PATTERN); matcher = pattern.matcher(value); - if (matcher.find() && setWithSystemEnv(matcher, sBuilder) && matcher.group(2) != null) { - sBuilder.append(matcher.group(2)); + if (matcher.find() && setWithSystemEnv(matcher, sBuilder)) { + // when a value is assigned to variable, e.g. ${PORT:8080} + if (Objects.nonNull(matcher.group(2))) { + sBuilder.append(matcher.group(2)); + return new Object[] { sBuilder.toString(), Boolean.TRUE }; + } + + // when nothing is assigned to variable, e.g. ${PORT:} + if (Objects.nonNull(matcher.group(1))) { + return new Object[] { StringUtils.EMPTY, Boolean.TRUE }; + } } } - return sBuilder; + + return new Object[] { sBuilder.toString(), Boolean.FALSE }; } /** @@ -158,10 +163,11 @@ private static StringBuilder resolveEnvironmentVariable(final String value) { * @return true if System.getenv returns a value */ private static boolean setWithSystemEnv(Matcher matcher, StringBuilder sBuilder) { - if (Objects.nonNull(matcher.group(1))) { - String envVarName = matcher.group(1); - String envVarValue = System.getenv(envVarName); - sBuilder.append(null == envVarValue ? StringUtils.EMPTY : envVarValue); + final String envVarName = matcher.group(1); + + if (Objects.nonNull(envVarName)) { + sBuilder.append(Optional.ofNullable(System.getenv(envVarName)) + .orElse(StringUtils.EMPTY)); } return StringUtils.isEmpty(sBuilder.toString()); diff --git a/src/main/resources/META-INF/native-image/com.github.switcherapi.client/switcher-client/reflect-config.json b/src/main/resources/META-INF/native-image/com.github.switcherapi.client/switcher-client/reflect-config.json new file mode 100644 index 00000000..b9bd1dc3 --- /dev/null +++ b/src/main/resources/META-INF/native-image/com.github.switcherapi.client/switcher-client/reflect-config.json @@ -0,0 +1,175 @@ +[ + { + "name": "com.github.switcherapi.client.model.Entry", + "condition": { + "typeReachable": "com.github.switcherapi.client.remote.dto.CriteriaRequest.GsonInputRequest" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.remote.dto.CriteriaRequest.GsonInputRequest", + "condition": { + "typeReachable": "com.github.switcherapi.client.model.Switcher" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.model.criteria.Config", + "condition": { + "typeReachable": "com.github.switcherapi.client.model.criteria.Snapshot" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.model.criteria.Criteria", + "condition": { + "typeReachable": "com.github.switcherapi.client.model.criteria.Snapshot" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.model.criteria.Domain", + "condition": { + "typeReachable": "com.github.switcherapi.client.model.criteria.Snapshot" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.model.criteria.Group", + "condition": { + "typeReachable": "com.github.switcherapi.client.model.criteria.Snapshot" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.model.criteria.Snapshot", + "condition": { + "typeReachable": "com.github.switcherapi.client.SwitcherExecutor" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.model.criteria.Strategy", + "condition": { + "typeReachable": "com.github.switcherapi.client.model.criteria.Snapshot" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.model.criteria.SwitcherElement", + "allDeclaredFields": true + }, + { + "name": "com.github.switcherapi.client.remote.dto.SwitchersCheck", + "condition": { + "typeReachable": "com.github.switcherapi.client.remote.ClientWSImpl" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.remote.dto.AuthRequest", + "condition": { + "typeReachable": "com.github.switcherapi.client.remote.ClientWSImpl" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.remote.dto.AuthResponse", + "condition": { + "typeReachable": "com.github.switcherapi.client.remote.ClientWSImpl" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.remote.dto.SnapshotVersionResponse", + "condition": { + "typeReachable": "com.github.switcherapi.client.remote.ClientWSImpl" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + }, + { + "name": "com.github.switcherapi.client.remote.dto.CriteriaResponse", + "condition": { + "typeReachable": "com.github.switcherapi.client.remote.ClientWSImpl" + }, + "allDeclaredFields": true, + "methods": [ + { + "name": "", + "parameterTypes": [] + } + ] + } +] \ No newline at end of file diff --git a/src/main/resources/META-INF/native-image/com.github.switcherapi.client/switcher-client/resource-config.json b/src/main/resources/META-INF/native-image/com.github.switcherapi.client/switcher-client/resource-config.json new file mode 100644 index 00000000..d47e6561 --- /dev/null +++ b/src/main/resources/META-INF/native-image/com.github.switcherapi.client/switcher-client/resource-config.json @@ -0,0 +1,18 @@ +{ + "resources": { + "includes": [ + { + "pattern": "switcherapi.*\\.properties$", + "condition": { + "typeReachable": "com.github.switcherapi.client.SwitcherContextBase" + } + }, + { + "pattern": "snapshots/.*\\.json$", + "condition": { + "typeReachable": "com.github.switcherapi.client.SwitcherContextBase" + } + } + ] + } +} \ No newline at end of file diff --git a/src/test/java/com/github/switcherapi/SwitchersBaseNative.java b/src/test/java/com/github/switcherapi/SwitchersBaseNative.java new file mode 100644 index 00000000..c40418e5 --- /dev/null +++ b/src/test/java/com/github/switcherapi/SwitchersBaseNative.java @@ -0,0 +1,24 @@ +package com.github.switcherapi; + +import com.github.switcherapi.client.SwitcherContextBase; + +public class SwitchersBaseNative extends SwitcherContextBase { + + public static final String USECASE11 = "USECASE11"; + + @Override + public void configureClient() { + super.registerSwitcherKeys(USECASE11); + super.configureClient(); + } + + public static SwitchersBaseNative buildSwitcherClientConfigMinimal(String url) { + SwitchersBaseNative context = new SwitchersBaseNative(); + context.setUrl(url); + context.setApikey("[API-KEY]"); + context.setDomain("domain"); + context.setComponent("component"); + return context; + } + +} diff --git a/src/test/java/com/github/switcherapi/client/SwitcherBasicCriteriaResponseTest.java b/src/test/java/com/github/switcherapi/client/SwitcherBasicCriteriaResponseTest.java index fc3f5c7a..5cb25d7b 100644 --- a/src/test/java/com/github/switcherapi/client/SwitcherBasicCriteriaResponseTest.java +++ b/src/test/java/com/github/switcherapi/client/SwitcherBasicCriteriaResponseTest.java @@ -2,7 +2,7 @@ import com.github.switcherapi.Switchers; import com.github.switcherapi.client.model.Switcher; -import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.model.SwitcherResult; import com.github.switcherapi.fixture.MetadataErrorSample; import com.github.switcherapi.fixture.MetadataSample; import com.github.switcherapi.fixture.MockWebServerHelper; @@ -59,7 +59,7 @@ void shouldReturnCriteriaResponse() { //test Switcher switcher = Switchers.getSwitcher(Switchers.REMOTE_KEY); - CriteriaResponse response = switcher.submit(); + SwitcherResult response = switcher.submit(); assertTrue(response.isItOn()); assertEquals("Success", response.getReason()); @@ -75,7 +75,7 @@ void shouldReturnCriteriaResponseWithInputs() { //test Switcher switcher = Switchers.getSwitcher(Switchers.REMOTE_KEY); - CriteriaResponse response = switcher + SwitcherResult response = switcher .checkValue("value") .checkNumeric("10") .submit(); @@ -94,7 +94,7 @@ void shouldReturnCriteriaResponseWithMetadata() { //test Switcher switcher = Switchers.getSwitcher(Switchers.REMOTE_KEY); - CriteriaResponse response = switcher.submit(); + SwitcherResult response = switcher.submit(); assertEquals("123", response.getMetadata(MetadataSample.class).getTransactionId()); } @@ -109,7 +109,7 @@ void shouldReturnCriteriaResponseWithWrongMetadata() { //test Switcher switcher = Switchers.getSwitcher(Switchers.REMOTE_KEY); - CriteriaResponse response = switcher.submit(); + SwitcherResult response = switcher.submit(); assertNotNull(response.getMetadata(MetadataSample.class)); assertNull(response.getMetadata(MetadataSample.class).getTransactionId()); diff --git a/src/test/java/com/github/switcherapi/client/SwitcherBypassTest.java b/src/test/java/com/github/switcherapi/client/SwitcherBypassTest.java index 9d509705..bb2ce7ec 100644 --- a/src/test/java/com/github/switcherapi/client/SwitcherBypassTest.java +++ b/src/test/java/com/github/switcherapi/client/SwitcherBypassTest.java @@ -2,7 +2,7 @@ import com.github.switcherapi.client.model.StrategyValidator; import com.github.switcherapi.client.model.Switcher; -import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.model.SwitcherResult; import com.github.switcherapi.client.test.SwitcherTest; import com.github.switcherapi.client.test.SwitcherTestValue; import com.github.switcherapi.client.test.SwitcherTestWhen; @@ -184,9 +184,9 @@ void shouldReturnSwitcherBypassedAsReason() { //test Switcher switcher = getSwitcher(USECASE111); - CriteriaResponse criteriaResponse = switcher.submit(); - assertTrue(criteriaResponse.isItOn()); - assertEquals("Switcher bypassed", criteriaResponse.getReason()); + SwitcherResult switcherResult = switcher.submit(); + assertTrue(switcherResult.isItOn()); + assertEquals("Switcher bypassed", switcherResult.getReason()); } @SwitcherTest(switchers = { @@ -219,8 +219,8 @@ void shouldReturnWithMetadata() { //test Switcher switcher = getSwitcher(USECASE111); - CriteriaResponse criteriaResponse = switcher.submit(); - assertEquals("123", criteriaResponse.getMetadata(MetadataSample.class).getTransactionId()); + SwitcherResult switcherResult = switcher.submit(); + assertEquals("123", switcherResult.getMetadata(MetadataSample.class).getTransactionId()); } @SwitcherTest(switchers = { @@ -234,12 +234,12 @@ void shouldReturnWithMetadata_usingMultipleSwitchersAnnotation() { //test Switcher switcher = getSwitcher(USECASE111); - CriteriaResponse criteriaResponse = switcher.submit(); - assertEquals("123", criteriaResponse.getMetadata(MetadataSample.class).getTransactionId()); + SwitcherResult switcherResult = switcher.submit(); + assertEquals("123", switcherResult.getMetadata(MetadataSample.class).getTransactionId()); switcher = getSwitcher(USECASE112); - criteriaResponse = switcher.submit(); - assertEquals("321", criteriaResponse.getMetadata(MetadataErrorSample.class).getErrorId()); + switcherResult = switcher.submit(); + assertEquals("321", switcherResult.getMetadata(MetadataErrorSample.class).getErrorId()); } @Test diff --git a/src/test/java/com/github/switcherapi/client/SwitcherConfigNativeTest.java b/src/test/java/com/github/switcherapi/client/SwitcherConfigNativeTest.java index 73f207b8..aa05535a 100644 --- a/src/test/java/com/github/switcherapi/client/SwitcherConfigNativeTest.java +++ b/src/test/java/com/github/switcherapi/client/SwitcherConfigNativeTest.java @@ -1,14 +1,16 @@ package com.github.switcherapi.client; -import com.github.switcherapi.SwitchersBase; +import com.github.switcherapi.SwitchersBaseNative; import com.github.switcherapi.fixture.MockWebServerHelper; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.io.IOException; +import java.util.HashSet; +import java.util.Set; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; class SwitcherConfigNativeTest extends MockWebServerHelper { @@ -24,29 +26,39 @@ static void tearDown() throws IOException { @Test void shouldUseNativeContext() { - SwitchersBase context = buildSwitcherClientConfigMinimal(new SwitchersBase(), String.format("http://localhost:%s", mockBackEnd.getPort())); + SwitchersBaseNative context = SwitchersBaseNative.buildSwitcherClientConfigMinimal(String.format("http://localhost:%s", mockBackEnd.getPort())); context.configureClient(); - givenResponse(generateMockAuth(10)); - givenResponse(generateCriteriaResponse("true", false)); + givenResponse(generateMockAuth(10)); //auth + givenResponse(generateCriteriaResponse("true", false)); //criteria - assertTrue(SwitchersBase.getSwitcher(SwitchersBase.USECASE11).isItOn()); + assertTrue(SwitchersBaseNative.getSwitcher(SwitchersBaseNative.USECASE11).isItOn()); } @Test - void shouldUseNativeContextFromProperties() { - SwitchersBase context = new SwitchersBase(); - context.configureClient("switcherapi-native"); + void shouldUseNativeAndValidateSwitchers() { + SwitchersBaseNative context = SwitchersBaseNative.buildSwitcherClientConfigMinimal(String.format("http://localhost:%s", mockBackEnd.getPort())); + context.configureClient(); + + final Set notFound = new HashSet<>(); + givenResponse(generateMockAuth(10)); //auth + givenResponse(generateCheckSwitchersResponse(notFound)); //criteria/check_switchers - assertTrue(SwitchersBase.getSwitcher(SwitchersBase.USECASE11).isItOn()); + assertDoesNotThrow(SwitchersBaseNative::checkSwitchers); } - private T buildSwitcherClientConfigMinimal(T classConfig, String url) { - classConfig.setUrl(url); - classConfig.setApikey("[API-KEY]"); - classConfig.setDomain("domain"); - classConfig.setComponent("component"); - return classConfig; + @Test + void shouldUseNativeContextFromProperties() { + SwitchersBaseNative context = new SwitchersBaseNative(); + context.registerSwitcherKeys(SwitchersBaseNative.USECASE11); + context.configureClient("switcherapi-native"); + + assertTrue(SwitchersBaseNative.getSwitcher(SwitchersBaseNative.USECASE11).isItOn()); + assertEquals("switcher-client", context.component); + assertEquals("switcher-domain", context.domain); + assertEquals("[API_KEY]", context.apikey); + assertEquals("http://localhost:3000", context.url); + assertEquals("fixture1", context.environment); } } diff --git a/src/test/java/com/github/switcherapi/client/SwitcherLocal1Test.java b/src/test/java/com/github/switcherapi/client/SwitcherLocal1Test.java index f7e4ea69..03cc6f92 100644 --- a/src/test/java/com/github/switcherapi/client/SwitcherLocal1Test.java +++ b/src/test/java/com/github/switcherapi/client/SwitcherLocal1Test.java @@ -106,9 +106,8 @@ static Stream dateTestArguments() { void localShouldTest_dateValidation(String useCaseKey, String input, boolean expected) { Switcher switcher = Switchers.getSwitcher(useCaseKey); Entry entry = Entry.build(StrategyValidator.DATE, input); - - switcher.prepareEntry(entry); - assertEquals(expected, switcher.isItOn()); + + assertEquals(expected, switcher.prepareEntry(entry).isItOn()); } @ParameterizedTest() diff --git a/src/test/java/com/github/switcherapi/client/SwitcherSnapshotAutoUpdateTest.java b/src/test/java/com/github/switcherapi/client/SwitcherSnapshotAutoUpdateTest.java index 965ad204..fbb4ceb5 100644 --- a/src/test/java/com/github/switcherapi/client/SwitcherSnapshotAutoUpdateTest.java +++ b/src/test/java/com/github/switcherapi/client/SwitcherSnapshotAutoUpdateTest.java @@ -1,7 +1,7 @@ package com.github.switcherapi.client; import com.github.switcherapi.Switchers; -import com.github.switcherapi.client.model.criteria.Criteria; +import com.github.switcherapi.client.model.criteria.Data; import com.github.switcherapi.client.model.criteria.Domain; import com.github.switcherapi.client.model.criteria.Snapshot; import com.github.switcherapi.client.utils.SnapshotLoader; @@ -60,9 +60,9 @@ void restoreStubs() { static void generateFixture(String environment) { final Snapshot mockedSnapshot = new Snapshot(); - final Criteria criteria = new Criteria(); - criteria.setDomain(DOMAIN_OUTDATED); - mockedSnapshot.setData(criteria); + final Data data = new Data(); + data.setDomain(DOMAIN_OUTDATED); + mockedSnapshot.setData(data); SnapshotLoader.saveSnapshot(mockedSnapshot, SNAPSHOTS_LOCAL, environment); } diff --git a/src/test/java/com/github/switcherapi/client/SwitcherSnapshotValidationTest.java b/src/test/java/com/github/switcherapi/client/SwitcherSnapshotValidationTest.java index 9291f2c1..01014688 100644 --- a/src/test/java/com/github/switcherapi/client/SwitcherSnapshotValidationTest.java +++ b/src/test/java/com/github/switcherapi/client/SwitcherSnapshotValidationTest.java @@ -126,7 +126,7 @@ void shouldValidateAndLoadSnapshot_whenLocal() { void shouldNotValidateAndLoadSnapshot_serviceUnavailable() { //given Switchers.configure(ContextBuilder.builder() - .local(true) + .local(false) .snapshotAutoLoad(false) .snapshotLocation(RESOURCES_PATH) .environment("default")); diff --git a/src/test/java/com/github/switcherapi/client/model/ModelTest.java b/src/test/java/com/github/switcherapi/client/model/ModelTest.java index 137fd45c..85ce136c 100644 --- a/src/test/java/com/github/switcherapi/client/model/ModelTest.java +++ b/src/test/java/com/github/switcherapi/client/model/ModelTest.java @@ -3,7 +3,7 @@ import org.junit.jupiter.api.Test; import com.github.switcherapi.client.model.criteria.Config; -import com.github.switcherapi.client.model.criteria.Criteria; +import com.github.switcherapi.client.model.criteria.Data; import com.github.switcherapi.client.model.criteria.Domain; import com.github.switcherapi.client.model.criteria.Group; import com.github.switcherapi.client.model.criteria.Snapshot; @@ -76,13 +76,13 @@ void testCriteriaPackage() { assertEquals(10000000000L, domain.getVersion()); assertSame(groups, domain.getGroup()); - final Criteria criteria = new Criteria(); - criteria.setDomain(domain); + final Data data = new Data(); + data.setDomain(domain); final Snapshot snapshot = new Snapshot(); - snapshot.setData(criteria); + snapshot.setData(data); - assertSame(criteria, snapshot.getData()); + assertSame(data, snapshot.getData()); } } diff --git a/src/test/java/com/github/switcherapi/client/remote/ClientRemoteTest.java b/src/test/java/com/github/switcherapi/client/remote/ClientRemoteTest.java index 7114428e..4303218c 100644 --- a/src/test/java/com/github/switcherapi/client/remote/ClientRemoteTest.java +++ b/src/test/java/com/github/switcherapi/client/remote/ClientRemoteTest.java @@ -4,8 +4,9 @@ import com.github.switcherapi.client.ContextBuilder; import com.github.switcherapi.client.SwitcherProperties; import com.github.switcherapi.client.model.Switcher; -import com.github.switcherapi.client.model.criteria.SwitchersCheck; -import com.github.switcherapi.client.model.response.CriteriaResponse; +import com.github.switcherapi.client.remote.dto.SwitchersCheck; +import com.github.switcherapi.client.remote.dto.CriteriaRequest; +import com.github.switcherapi.client.model.SwitcherResult; import com.github.switcherapi.client.service.SwitcherValidator; import com.github.switcherapi.client.service.ValidatorService; import com.github.switcherapi.client.service.local.ClientLocal; @@ -71,10 +72,11 @@ void shouldExecuteCriteria() { SwitcherValidator validatorService = new ValidatorService(); ClientLocal clientLocal = new ClientLocalService(validatorService); - Switcher switcher = new Switcher("KEY", new SwitcherRemoteService(clientRemote, new SwitcherLocalService(clientRemote, clientLocal, Switchers.getSwitcherProperties()))); + Switcher switcher = new Switcher("KEY", new SwitcherRemoteService(clientRemote, + new SwitcherLocalService(clientRemote, clientLocal, Switchers.getSwitcherProperties()))); //test - CriteriaResponse actual = clientRemote.executeCriteria(switcher); + SwitcherResult actual = SwitcherResult.buildResultFromRemote(clientRemote.executeCriteria(CriteriaRequest.build(switcher))); assertTrue(actual.isItOn()); } diff --git a/src/test/java/com/github/switcherapi/client/service/local/SwitcherLocalServiceTest.java b/src/test/java/com/github/switcherapi/client/service/local/SwitcherLocalServiceTest.java index f6e77cfe..e0c4953f 100644 --- a/src/test/java/com/github/switcherapi/client/service/local/SwitcherLocalServiceTest.java +++ b/src/test/java/com/github/switcherapi/client/service/local/SwitcherLocalServiceTest.java @@ -62,6 +62,15 @@ void shouldNotifyWithError() { assertFalse(service.notifyChange("defect_default.json")); } + + @Test + void shouldNotifyWithErrorResources() { + SwitchersBase.configure(ContextBuilder.builder() + .snapshotLocation("") + .environment("defect_default")); + + assertFalse(service.notifyChange("defect_default.json")); + } @Test void shouldNotifyWithSuccess() { @@ -70,6 +79,15 @@ void shouldNotifyWithSuccess() { assertTrue(service.notifyChange("snapshot_watcher.json")); } + + @Test + void shouldNotifyWithSuccessResources() { + SwitchersBase.configure(ContextBuilder.builder() + .snapshotLocation("") + .environment("snapshot_watcher")); + + assertTrue(service.notifyChange("snapshot_watcher.json")); + } @Test void shouldNotifyWithSuccess_customHandler() { diff --git a/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherTest.java b/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherTest.java index 7307f6a0..2f978e92 100644 --- a/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherTest.java +++ b/src/test/java/com/github/switcherapi/client/utils/SnapshotWatcherTest.java @@ -3,7 +3,7 @@ import com.github.switcherapi.SwitchersBase; import com.github.switcherapi.client.ContextBuilder; import com.github.switcherapi.client.model.Switcher; -import com.github.switcherapi.client.model.criteria.Criteria; +import com.github.switcherapi.client.model.criteria.Data; import com.github.switcherapi.client.model.criteria.Snapshot; import com.github.switcherapi.fixture.CountDownHelper; import com.google.gson.Gson; @@ -64,20 +64,20 @@ static void removeGeneratedFiles() throws IOException { static void generateFixture() { final Snapshot mockedSnapshot = new Snapshot(); - final Criteria criteria = new Criteria(); - criteria.setDomain(SnapshotLoader.loadSnapshot(SNAPSHOTS_LOCAL + "/snapshot_watcher.json")); - mockedSnapshot.setData(criteria); + final Data data = new Data(); + data.setDomain(SnapshotLoader.loadSnapshot(SNAPSHOTS_LOCAL + "/snapshot_watcher.json")); + mockedSnapshot.setData(data); SnapshotLoader.saveSnapshot(mockedSnapshot, SNAPSHOTS_LOCAL, "generated_watcher_default"); } void changeFixture() { final Snapshot mockedSnapshot = new Snapshot(); - final Criteria criteria = new Criteria(); - criteria.setDomain(SnapshotLoader.loadSnapshot(SNAPSHOTS_LOCAL + "/snapshot_watcher.json")); - mockedSnapshot.setData(criteria); + final Data data = new Data(); + data.setDomain(SnapshotLoader.loadSnapshot(SNAPSHOTS_LOCAL + "/snapshot_watcher.json")); + mockedSnapshot.setData(data); - criteria.getDomain().setActivated(false); + data.getDomain().setActivated(false); final Gson gson = new GsonBuilder().setPrettyPrinting().create(); writeFixture(gson.toJson(mockedSnapshot)); diff --git a/src/test/java/com/github/switcherapi/client/utils/SwitcherUtilsTest.java b/src/test/java/com/github/switcherapi/client/utils/SwitcherUtilsTest.java index 36a90dfa..b3b67b9b 100644 --- a/src/test/java/com/github/switcherapi/client/utils/SwitcherUtilsTest.java +++ b/src/test/java/com/github/switcherapi/client/utils/SwitcherUtilsTest.java @@ -118,6 +118,7 @@ static Stream envArguments() { return Stream.of( Arguments.of("default", "default"), Arguments.of("${PORT:8080}", "8080"), + Arguments.of("${SNAPSHOT_LOCAL:}", ""), Arguments.of("${ENVIRONMENT}", "staging") ); } diff --git a/src/test/java/com/github/switcherapi/fixture/MockWebServerHelper.java b/src/test/java/com/github/switcherapi/fixture/MockWebServerHelper.java index 6478e69e..bec19f66 100644 --- a/src/test/java/com/github/switcherapi/fixture/MockWebServerHelper.java +++ b/src/test/java/com/github/switcherapi/fixture/MockWebServerHelper.java @@ -1,10 +1,10 @@ package com.github.switcherapi.fixture; -import com.github.switcherapi.client.model.Switcher; -import com.github.switcherapi.client.model.criteria.Criteria; +import com.github.switcherapi.client.model.criteria.Data; import com.github.switcherapi.client.model.criteria.Snapshot; -import com.github.switcherapi.client.model.criteria.SwitchersCheck; +import com.github.switcherapi.client.remote.dto.SwitchersCheck; import com.github.switcherapi.client.remote.ClientWSImpl; +import com.github.switcherapi.client.remote.dto.CriteriaRequest; import com.github.switcherapi.client.utils.SnapshotLoader; import com.github.switcherapi.client.utils.SwitcherUtils; import com.google.gson.Gson; @@ -72,9 +72,9 @@ protected MockResponse generateSnapshotResponse(String resourcesPath) { */ protected MockResponse generateSnapshotResponse(String snapshotFile, String resourcesPath) { final Snapshot mockedSnapshot = new Snapshot(); - final Criteria criteria = new Criteria(); - criteria.setDomain(SnapshotLoader.loadSnapshot(resourcesPath + "/" + snapshotFile)); - mockedSnapshot.setData(criteria); + final Data data = new Data(); + data.setDomain(SnapshotLoader.loadSnapshot(resourcesPath + "/" + snapshotFile)); + mockedSnapshot.setData(data); Gson gson = new Gson(); MockResponse.Builder builder = new MockResponse.Builder(); @@ -109,7 +109,7 @@ protected MockResponse generateStatusResponse(String code) { } /** - * @see ClientWSImpl#executeCriteria(Switcher, String) + * @see ClientWSImpl#executeCriteria(CriteriaRequest, String) * * @param result returned by the criteria execution * @param reason if you want to display along with the result @@ -124,7 +124,7 @@ protected MockResponse generateCriteriaResponse(String result, boolean reason) { } /** - * @see ClientWSImpl#executeCriteria(Switcher, String) + * @see ClientWSImpl#executeCriteria(CriteriaRequest, String) * * @param result returned by the criteria execution * @return Generated mock /criteria response @@ -134,7 +134,7 @@ protected MockResponse generateCriteriaResponse(String result) { } /** - * @see ClientWSImpl#executeCriteria(Switcher, String) + * @see ClientWSImpl#executeCriteria(CriteriaRequest, String) * * @param result returned by the criteria execution * @param reason returned by the criteria execution @@ -155,7 +155,7 @@ protected MockResponse generateCriteriaResponse(String result, String reason) { } /** - * @see ClientWSImpl#executeCriteria(Switcher, String) + * @see ClientWSImpl#executeCriteria(CriteriaRequest, String) * * @param metadata returned by the criteria execution * @return Generated mock /criteria response diff --git a/src/test/java/com/github/switcherapi/playground/ClientPlayground.java b/src/test/java/com/github/switcherapi/playground/ClientPlayground.java index f1626df2..4b0f048c 100644 --- a/src/test/java/com/github/switcherapi/playground/ClientPlayground.java +++ b/src/test/java/com/github/switcherapi/playground/ClientPlayground.java @@ -1,8 +1,5 @@ package com.github.switcherapi.playground; -import static com.github.switcherapi.playground.Features.*; - -import com.github.switcherapi.client.ContextBuilder; import com.github.switcherapi.client.model.Switcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -11,6 +8,9 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import static com.github.switcherapi.playground.Features.MY_SWITCHER; +import static com.github.switcherapi.playground.Features.getSwitcher; + public class ClientPlayground { static final Logger logger = LoggerFactory.getLogger(ClientPlayground.class); @@ -18,16 +18,7 @@ public class ClientPlayground { private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public static void test() { - configure(ContextBuilder.builder() - .context(Features.class.getCanonicalName()) - .url("https://api.switcherapi.com") - .apiKey("[API_KEY]") - .domain("Playground") - .local(true) - .snapshotLocation("src/test/resources/snapshot/playground") - .component("switcher-playground")); - - initializeClient(); + new Features().configureClient(); Switcher switcher = getSwitcher(MY_SWITCHER); scheduler.scheduleAtFixedRate(() -> { diff --git a/src/test/java/com/github/switcherapi/playground/Features.java b/src/test/java/com/github/switcherapi/playground/Features.java index 964a43b6..04784103 100644 --- a/src/test/java/com/github/switcherapi/playground/Features.java +++ b/src/test/java/com/github/switcherapi/playground/Features.java @@ -1,5 +1,6 @@ package com.github.switcherapi.playground; +import com.github.switcherapi.client.ContextBuilder; import com.github.switcherapi.client.SwitcherContextBase; import com.github.switcherapi.client.SwitcherKey; @@ -8,4 +9,17 @@ public class Features extends SwitcherContextBase { @SwitcherKey public static final String MY_SWITCHER = "MY_SWITCHER"; + @Override + protected void configureClient() { + configure(ContextBuilder.builder() + .context(Features.class.getCanonicalName()) + .url("https://api.switcherapi.com") + .apiKey("[API_KEY]") + .component("switcher-playground") + .domain("Playground") + .local(true) + .snapshotLocation("/snapshot/playground")); + + initializeClient(); + } } From ed8b290507ff901d12056cda9ce4759ff7275eee Mon Sep 17 00:00:00 2001 From: petruki <31597636+petruki@users.noreply.github.com> Date: Wed, 27 Nov 2024 17:42:47 -0800 Subject: [PATCH 2/3] Removed dto unused code --- .../client/model/SwitcherResult.java | 7 ++-- .../client/remote/ClientWSImpl.java | 1 - .../client/remote/dto/CriteriaResponse.java | 33 +++++-------------- 3 files changed, 10 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/github/switcherapi/client/model/SwitcherResult.java b/src/main/java/com/github/switcherapi/client/model/SwitcherResult.java index 8435650b..8fe40739 100644 --- a/src/main/java/com/github/switcherapi/client/model/SwitcherResult.java +++ b/src/main/java/com/github/switcherapi/client/model/SwitcherResult.java @@ -1,9 +1,6 @@ package com.github.switcherapi.client.model; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; +import java.util.*; import com.github.switcherapi.client.remote.dto.CriteriaResponse; import com.google.gson.Gson; @@ -32,6 +29,7 @@ public class SwitcherResult { public SwitcherResult() { entryWhen = new HashMap<>(); + entry = new ArrayList<>(); } private SwitcherResult(final boolean result, final String reason, final Switcher switcher) { @@ -80,7 +78,6 @@ public static SwitcherResult buildResultFromRemote(CriteriaResponse criteriaResp switcherResult.setResult(criteriaResponse.getResult()); switcherResult.setReason(criteriaResponse.getReason()); switcherResult.setMetadata(criteriaResponse.getMetadata()); - switcherResult.setEntry(criteriaResponse.getEntry()); return switcherResult; } diff --git a/src/main/java/com/github/switcherapi/client/remote/ClientWSImpl.java b/src/main/java/com/github/switcherapi/client/remote/ClientWSImpl.java index 661010ab..91d69da8 100644 --- a/src/main/java/com/github/switcherapi/client/remote/ClientWSImpl.java +++ b/src/main/java/com/github/switcherapi/client/remote/ClientWSImpl.java @@ -73,7 +73,6 @@ public CriteriaResponse executeCriteria(final CriteriaRequest criteriaRequest, f final CriteriaResponse criteriaResponse = gson.fromJson(response.body(), CriteriaResponse.class); criteriaResponse.setSwitcherKey(criteriaRequest.getSwitcherKey()); - criteriaResponse.setEntry(criteriaRequest.getEntry()); return criteriaResponse; } catch (Exception e) { return exceptionHandler(e, url); diff --git a/src/main/java/com/github/switcherapi/client/remote/dto/CriteriaResponse.java b/src/main/java/com/github/switcherapi/client/remote/dto/CriteriaResponse.java index f1b0ddc1..b8d4789b 100644 --- a/src/main/java/com/github/switcherapi/client/remote/dto/CriteriaResponse.java +++ b/src/main/java/com/github/switcherapi/client/remote/dto/CriteriaResponse.java @@ -1,9 +1,5 @@ package com.github.switcherapi.client.remote.dto; -import com.github.switcherapi.client.model.Entry; - -import java.util.List; - public class CriteriaResponse { private boolean result; @@ -14,32 +10,18 @@ public class CriteriaResponse { private String switcherKey; - protected List entry; - public boolean getResult() { return result; } - public void setResult(boolean result) { - this.result = result; - } - public String getReason() { return reason; } - public void setReason(String reason) { - this.reason = reason; - } - public Object getMetadata() { return metadata; } - public void setMetadata(Object metadata) { - this.metadata = metadata; - } - public String getSwitcherKey() { return switcherKey; } @@ -48,12 +30,13 @@ public void setSwitcherKey(String switcherKey) { this.switcherKey = switcherKey; } - public List getEntry() { - return entry; + @Override + public String toString() { + return "CriteriaResponse{" + + "result=" + result + + ", reason='" + reason + '\'' + + ", metadata=" + metadata + + ", switcherKey='" + switcherKey + '\'' + + '}'; } - - public void setEntry(List entry) { - this.entry = entry; - } - } From 1150d5b678751b74e69e30afe56ede0954c47113 Mon Sep 17 00:00:00 2001 From: petruki <31597636+petruki@users.noreply.github.com> Date: Wed, 27 Nov 2024 17:47:18 -0800 Subject: [PATCH 3/3] Fixes code smells --- .../switcherapi/client/SwitcherConfig.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/github/switcherapi/client/SwitcherConfig.java b/src/main/java/com/github/switcherapi/client/SwitcherConfig.java index a400e43a..baf9266a 100644 --- a/src/main/java/com/github/switcherapi/client/SwitcherConfig.java +++ b/src/main/java/com/github/switcherapi/client/SwitcherConfig.java @@ -38,17 +38,17 @@ protected void updateSwitcherConfig(SwitcherProperties properties) { setTimeout(properties.getInt(ContextKey.TIMEOUT_MS)); setPoolSize(properties.getInt(ContextKey.POOL_CONNECTION_SIZE)); - SnapshotConfig snapshot = new SnapshotConfig(); - snapshot.setLocation(properties.getValue(ContextKey.SNAPSHOT_LOCATION)); - snapshot.setAuto(properties.getBoolean(ContextKey.SNAPSHOT_AUTO_LOAD)); - snapshot.setSkipValidation(properties.getBoolean(ContextKey.SNAPSHOT_SKIP_VALIDATION)); - snapshot.setUpdateInterval(properties.getValue(ContextKey.SNAPSHOT_AUTO_UPDATE_INTERVAL)); - setSnapshot(snapshot); - - TruststoreConfig truststore = new TruststoreConfig(); - truststore.setPath(properties.getValue(ContextKey.TRUSTSTORE_PATH)); - truststore.setPassword(properties.getValue(ContextKey.TRUSTSTORE_PASSWORD)); - setTruststore(truststore); + SnapshotConfig snapshotConfig = new SnapshotConfig(); + snapshotConfig.setLocation(properties.getValue(ContextKey.SNAPSHOT_LOCATION)); + snapshotConfig.setAuto(properties.getBoolean(ContextKey.SNAPSHOT_AUTO_LOAD)); + snapshotConfig.setSkipValidation(properties.getBoolean(ContextKey.SNAPSHOT_SKIP_VALIDATION)); + snapshotConfig.setUpdateInterval(properties.getValue(ContextKey.SNAPSHOT_AUTO_UPDATE_INTERVAL)); + setSnapshot(snapshotConfig); + + TruststoreConfig truststoreConfig = new TruststoreConfig(); + truststoreConfig.setPath(properties.getValue(ContextKey.TRUSTSTORE_PATH)); + truststoreConfig.setPassword(properties.getValue(ContextKey.TRUSTSTORE_PASSWORD)); + setTruststore(truststoreConfig); } /**