Skip to content

Commit 9150161

Browse files
authored
refactor: extend logging for happy cases (#66)
<!-- Please describe your pull request here. --> ## References #65 <!-- References to relevant GitHub issues and pull requests, esp. upstream and downstream changes --> ## Submitter checklist - [ ] Recommended: Join [WireMock Slack](https://slack.wiremock.org/) to get any help in `#help-contributing` or a project-specific channel like `#wiremock-java` - [ ] Recommended: If you participate in Hacktoberfest 2023, make sure you're [signed up](https://wiremock.org/events/hacktoberfest/) there and in the WireMock form - [ ] The PR request is well described and justified, including the body and the references - [ ] The PR title represents the desired changelog entry - [ ] The repository's code style is followed (see the contributing guide) - [ ] Test coverage that demonstrates that the change works as expected - [ ] For new features, there's necessary documentation in this pull request or in a subsequent PR to [wiremock.org](https://github.com/wiremock/wiremock.org) <!-- Put an `x` into the [ ] to show you have filled the information. The template comes from https://github.com/wiremock/.github/blob/main/.github/pull_request_template.md You can override it by creating .github/pull_request_template.md in your own repository -->
1 parent 65b5230 commit 9150161

File tree

6 files changed

+140
-33
lines changed

6 files changed

+140
-33
lines changed

src/main/java/org/wiremock/extensions/state/extensions/DeleteStateEventListener.java

Lines changed: 48 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232
import java.util.Objects;
3333
import java.util.Optional;
3434

35+
import static org.wiremock.extensions.state.internal.ExtensionLogger.logger;
36+
3537
/**
3638
* Event listener to trigger state context deletion.
3739
* <p>
@@ -75,41 +77,63 @@ public void beforeResponseSent(ServeEvent serveEvent, Parameters parameters) {
7577

7678
private void handleListDeletion(DeleteStateParameters.ListParameters listConfig, String contextName, Map<String, Object> model) {
7779
if (Boolean.TRUE.equals(listConfig.getDeleteFirst())) {
78-
contextManager.createOrUpdateContextList(contextName, maps -> {
79-
if (!maps.isEmpty()) maps.removeFirst();
80-
});
80+
deleteFirst(contextName);
8181
} else if (Boolean.TRUE.equals(listConfig.getDeleteLast())) {
82-
contextManager.createOrUpdateContextList(contextName, maps -> {
83-
if (!maps.isEmpty()) maps.removeLast();
84-
});
82+
deleteLast(contextName);
8583
} else if (StringUtils.isNotBlank(listConfig.getDeleteIndex())) {
86-
try {
87-
var index = Integer.parseInt(renderTemplate(model, listConfig.getDeleteIndex()));
88-
contextManager.createOrUpdateContextList(contextName, list -> list.remove(index));
89-
} catch (IndexOutOfBoundsException | NumberFormatException e) {
90-
throw createConfigurationError("List index '%s' does not exist or cannot be parsed: %s", listConfig.getDeleteIndex(), e.getMessage());
91-
}
84+
deleteIndex(listConfig, contextName, model);
9285
} else if (listConfig.getDeleteWhere() != null &&
9386
listConfig.getDeleteWhere().getProperty() != null &&
9487
listConfig.getDeleteWhere().getValue() != null
9588
) {
96-
var property = renderTemplate(model, listConfig.getDeleteWhere().getProperty());
97-
var value = renderTemplate(model, listConfig.getDeleteWhere().getValue());
89+
deleteWhere(listConfig, contextName, model);
90+
} else {
91+
throw createConfigurationError("Missing/invalid configuration for list: ");
92+
}
93+
}
94+
95+
private Long deleteFirst(String contextName) {
96+
return contextManager.createOrUpdateContextList(contextName, maps -> {
97+
if (!maps.isEmpty()) maps.removeFirst();
98+
logger().info(contextName, "list::deleteFirst");
99+
});
100+
}
101+
102+
private void deleteLast(String contextName) {
103+
contextManager.createOrUpdateContextList(contextName, maps -> {
104+
if (!maps.isEmpty()) maps.removeLast();
105+
logger().info(contextName, "list::deleteLast");
106+
});
107+
}
108+
109+
private void deleteIndex(DeleteStateParameters.ListParameters listConfig, String contextName, Map<String, Object> model) {
110+
try {
111+
var index = Integer.parseInt(renderTemplate(model, listConfig.getDeleteIndex()));
98112
contextManager.createOrUpdateContextList(contextName, list -> {
99-
var iterator = list.iterator();
100-
while (iterator.hasNext()) {
101-
var element = iterator.next();
102-
if (Objects.equals(element.getOrDefault(property, null), value)) {
103-
iterator.remove();
104-
break;
105-
}
106-
}
113+
list.remove(index);
114+
logger().info(contextName, String.format("list::deleteIndex(%d)", index));
107115
});
108-
} else {
109-
throw createConfigurationError("Missing/invalid configuration for list");
116+
} catch (IndexOutOfBoundsException | NumberFormatException e) {
117+
throw createConfigurationError("List index '%s' does not exist or cannot be parsed: %s", listConfig.getDeleteIndex(), e.getMessage());
110118
}
111119
}
112120

121+
private void deleteWhere(DeleteStateParameters.ListParameters listConfig, String contextName, Map<String, Object> model) {
122+
var property = renderTemplate(model, listConfig.getDeleteWhere().getProperty());
123+
var value = renderTemplate(model, listConfig.getDeleteWhere().getValue());
124+
contextManager.createOrUpdateContextList(contextName, list -> {
125+
var iterator = list.iterator();
126+
while (iterator.hasNext()) {
127+
var element = iterator.next();
128+
if (Objects.equals(element.getOrDefault(property, null), value)) {
129+
iterator.remove();
130+
logger().info(contextName, String.format("list::deleteWhere(property=%s)", property));
131+
break;
132+
}
133+
}
134+
});
135+
}
136+
113137
private String createContextName(Map<String, Object> model, DeleteStateParameters parameters) {
114138
var rawContext = Optional.ofNullable(parameters.getContext()).filter(StringUtils::isNotBlank).orElseThrow(() -> new ConfigurationException("no context specified"));
115139
String context = renderTemplate(model, rawContext);

src/main/java/org/wiremock/extensions/state/extensions/RecordStateEventListener.java

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232
import java.util.Optional;
3333
import java.util.stream.Collectors;
3434

35+
import static org.wiremock.extensions.state.internal.ExtensionLogger.logger;
36+
3537
/**
3638
* Event listener to trigger state context recording.
3739
* <p>
@@ -88,16 +90,31 @@ private void handleList(String contextName, Map<String, Object> model, RecordSta
8890
Optional.ofNullable(parameters.getList())
8991
.ifPresent(listConfiguration -> {
9092
Optional.ofNullable(listConfiguration.getAddFirst())
91-
.ifPresent(configuration ->
92-
contextManager.createOrUpdateContextList(contextName, list -> list.addFirst(getPropertiesFromConfiguration(model, configuration))));
93-
Optional.ofNullable(listConfiguration.getAddLast()).ifPresent(configuration ->
94-
contextManager.createOrUpdateContextList(contextName, list -> list.addLast(getPropertiesFromConfiguration(model, configuration))));
93+
.ifPresent(configuration -> addFirst(contextName, model, configuration));
94+
Optional.ofNullable(listConfiguration.getAddLast())
95+
.ifPresent(configuration -> addLast(contextName, model, configuration));
9596
}
9697
);
9798
}
9899

100+
private Long addFirst(String contextName, Map<String, Object> model, Map<String, String> configuration) {
101+
return contextManager.createOrUpdateContextList(contextName, list -> {
102+
list.addFirst(getPropertiesFromConfiguration(model, configuration));
103+
logger().info(contextName, "list::addFirst");
104+
});
105+
}
106+
107+
private Long addLast(String contextName, Map<String, Object> model, Map<String, String> configuration) {
108+
return contextManager.createOrUpdateContextList(contextName, list -> {
109+
list.addLast(getPropertiesFromConfiguration(model, configuration));
110+
logger().info(contextName, "list::addLast");
111+
});
112+
}
113+
99114
private String createContextName(Map<String, Object> model, Parameters parameters) {
100-
var rawContext = Optional.ofNullable(parameters.getString("context")).filter(StringUtils::isNotBlank).orElseThrow(() -> new ConfigurationException("no context specified"));
115+
var rawContext = Optional.ofNullable(parameters.getString("context"))
116+
.filter(StringUtils::isNotBlank)
117+
.orElseThrow(() -> new ConfigurationException("no context specified"));
101118
String context = renderTemplate(model, rawContext);
102119
if (StringUtils.isBlank(context)) {
103120
throw createConfigurationError("context cannot be blank");

src/main/java/org/wiremock/extensions/state/extensions/StateHandlerbarHelper.java

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
import java.util.stream.Stream;
3232

3333
import static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;
34+
import static org.wiremock.extensions.state.internal.ExtensionLogger.logger;
3435

3536
/**
3637
* Response templating helper to access state.
@@ -84,7 +85,11 @@ private Optional<Object> getProperty(String contextName, String property, String
8485
.map(it -> it.getFromContext(context))
8586
.orElseGet(() -> context.getProperties().get(property))
8687
)
87-
.or(() -> convertToPropertySpecificDefault(property, defaultValue));
88+
.or(() -> convertToPropertySpecificDefault(property, defaultValue))
89+
.map((obj) -> {
90+
logger().info(contextName, String.format("handlebar(property=%s)", property));
91+
return obj;
92+
});
8893
}
8994

9095
private Optional<Object> convertToPropertySpecificDefault(String property, String defaultValue) {
@@ -104,6 +109,10 @@ private Optional<Object> getList(String contextName, String list) {
104109
notifier().info("Path query failed: " + e.getMessage());
105110
return Optional.empty();
106111
}
112+
})
113+
.map((obj) -> {
114+
logger().info(contextName, "handlebar(list)");
115+
return obj;
107116
});
108117
}
109118

src/main/java/org/wiremock/extensions/state/extensions/StateRequestMatcher.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import java.util.stream.Collectors;
3636

3737
import static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;
38+
import static org.wiremock.extensions.state.internal.ExtensionLogger.logger;
3839

3940
/**
4041
* Request matcher for state.
@@ -82,6 +83,7 @@ private MatchResult hasContext(Map<String, Object> model, Parameters parameters,
8283
.map(context -> {
8384
List<Map.Entry<ContextMatcher, Object>> matchers = getMatches(parameters);
8485
if (matchers.isEmpty()) {
86+
logger().info(context, "hasContext matched");
8587
return MatchResult.exactMatch();
8688
} else {
8789
return calculateMatch(model, context, matchers);
@@ -103,6 +105,7 @@ private MatchResult calculateMatch(Map<String, Object> model, Context context, L
103105
private MatchResult hasNotContext(Map<String, Object> model, String template) {
104106
var context = renderTemplate(model, template);
105107
if (contextManager.getContext(context).isEmpty()) {
108+
logger().info(context, "hasNotContext matched");
106109
return MatchResult.exactMatch();
107110
} else {
108111
return MatchResult.noMatch();

src/main/java/org/wiremock/extensions/state/internal/ContextManager.java

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
import java.util.Map;
2222
import java.util.Optional;
2323
import java.util.function.Consumer;
24+
import java.util.function.Supplier;
25+
26+
import static org.wiremock.extensions.state.internal.ExtensionLogger.logger;
2427

2528
public class ContextManager {
2629

@@ -30,6 +33,11 @@ public ContextManager(Store<String, Object> store) {
3033
this.store = store;
3134
}
3235

36+
private static Supplier<Context> createNewContext(String contextName) {
37+
logger().info(contextName, "created");
38+
return () -> new Context(contextName);
39+
}
40+
3341
public Object getState(String contextName, String property) {
3442
synchronized (store) {
3543
return store.get(contextName).map(it -> ((Context) it).getProperties().get(property)).orElse(null);
@@ -51,6 +59,7 @@ public Optional<Context> getContext(String contextName) {
5159
public void deleteContext(String contextName) {
5260
synchronized (store) {
5361
store.remove(contextName);
62+
logger().info(contextName, "deleted");
5463
}
5564
}
5665

@@ -61,12 +70,14 @@ public Long createOrUpdateContextState(String contextName, Map<String, String> p
6170
.map(it -> {
6271
it.incUpdateCount();
6372
return it;
64-
}).orElseGet(() -> new Context(contextName));
73+
}).orElseGet(createNewContext(contextName));
6574
properties.forEach((k, v) -> {
66-
if(v.equals("null")) {
75+
if (v.equals("null")) {
6776
context.getProperties().remove(k);
77+
logger().info(contextName, String.format("property '%s' removed", k));
6878
} else {
6979
context.getProperties().put(k, v);
80+
logger().info(contextName, String.format("property '%s' updated", k));
7081
}
7182
});
7283
store.put(contextName, context);
@@ -81,7 +92,7 @@ public Long createOrUpdateContextList(String contextName, Consumer<LinkedList<Ma
8192
.map(it -> {
8293
it.incUpdateCount();
8394
return it;
84-
}).orElseGet(() -> new Context(contextName));
95+
}).orElseGet(createNewContext(contextName));
8596
consumer.accept(context.getList());
8697
store.put(contextName, context);
8798
return context.getUpdateCount();
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package org.wiremock.extensions.state.internal;
2+
3+
import com.github.tomakehurst.wiremock.common.Notifier;
4+
5+
import static com.github.tomakehurst.wiremock.common.LocalNotifier.notifier;
6+
7+
public class ExtensionLogger {
8+
9+
private static Notifier notifier;
10+
11+
private ExtensionLogger() {
12+
notifier = notifier();
13+
}
14+
15+
public static ExtensionLogger logger() {
16+
return InstanceHolder.instance;
17+
}
18+
19+
public void info(Context context, String message) {
20+
notifier.info(buildMessage(context.getContextName(), message));
21+
}
22+
23+
public void error(Context context, String message) {
24+
notifier.error(buildMessage(context.getContextName(), message));
25+
}
26+
27+
public void info(String contextName, String message) {
28+
notifier.info(buildMessage(contextName, message));
29+
}
30+
31+
public void error(String contextName, String message) {
32+
notifier.error(buildMessage(contextName, message));
33+
}
34+
35+
private String buildMessage(String contextName, String message) {
36+
return String.format("Context '%s': %s", contextName, message);
37+
}
38+
39+
private static final class InstanceHolder {
40+
private static final ExtensionLogger instance = new ExtensionLogger();
41+
}
42+
43+
}

0 commit comments

Comments
 (0)