Skip to content

Commit

Permalink
Format properly the code around async feature (#762)
Browse files Browse the repository at this point in the history
  • Loading branch information
yinan-symphony committed Apr 20, 2023
1 parent 3249074 commit 4a5a88f
Show file tree
Hide file tree
Showing 12 changed files with 104 additions and 87 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ public abstract class AbstractActivity<E, C extends ActivityContext<E>> {

public AbstractActivity() {
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setName("AbstractActivity-Thread")
.setPriority(Thread.NORM_PRIORITY)
.build();
.setName("Activity-Async-Thread")
.setPriority(Thread.NORM_PRIORITY)
.build();
executorService = Executors.newCachedThreadPool(threadFactory);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,34 @@
package com.symphony.bdk.core.activity;

import com.symphony.bdk.http.api.tracing.MDCUtils;

import org.apiguardian.api.API;

import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

@API(status = API.Status.INTERNAL)
public class ThreadFactoryBuilder {
class ThreadFactoryBuilder {
private String name = null;
private int priority = Thread.NORM_PRIORITY;

public ThreadFactoryBuilder setName(String name) {
if (name == null) {
throw new NullPointerException();
}

Objects.requireNonNull(name);
this.name = name;
return this;
}

public ThreadFactoryBuilder setPriority(int priority) {
if (priority > Thread.MAX_PRIORITY) {
throw new IllegalArgumentException(
String.format("Thread priority %s must be <= %s", priority, Thread.MAX_PRIORITY));
String.format("Thread priority %s must be <= %s", priority, Thread.MAX_PRIORITY));
}

if (priority < Thread.MIN_PRIORITY) {
throw new IllegalArgumentException(
String.format("Thread priority %s must be >= %s", priority, Thread.MIN_PRIORITY));
String.format("Thread priority %s must be >= %s", priority, Thread.MIN_PRIORITY));
}

this.priority = priority;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
import com.symphony.bdk.core.activity.model.ActivityType;
import com.symphony.bdk.core.service.message.MessageService;
import com.symphony.bdk.core.service.message.model.Message;

import org.apiguardian.api.API;

import javax.annotation.Nonnull;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Nonnull;

/**
* A help command listing all the commands that can be performed by an end-user through the chat.
*/
Expand All @@ -35,7 +37,7 @@ public HelpCommand(@Nonnull ActivityRegistry activityRegistry, @Nonnull MessageS
*/
@Override
public void onActivity(CommandContext context) {
List<String> infos = this.activityRegistry.getActivityList()
List<String> activities = this.activityRegistry.getActivityList()
.stream()
.map(AbstractActivity::getInfo)
.filter(info -> info.type().equals(ActivityType.COMMAND))
Expand All @@ -44,8 +46,8 @@ public void onActivity(CommandContext context) {
return info.description().isEmpty() ? String.format(str, "") : String.format(str, " - " + info.description());
})
.collect(Collectors.toList());
if (!infos.isEmpty()) {
String message = "<ul>" + String.join("\n", infos) + "</ul>";
if (!activities.isEmpty()) {
String message = "<ul>" + String.join("\n", activities) + "</ul>";
this.messageService.send(context.getStreamId(), Message.builder().content(message).build());
}
}
Expand All @@ -63,7 +65,7 @@ protected ActivityInfo info() {

@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (this == o) {return true;}

if (o instanceof SlashCommand) {
SlashCommand that = ((SlashCommand) o);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@
import com.symphony.bdk.core.activity.parsing.SlashCommandPattern;
import com.symphony.bdk.gen.api.model.V4Initiator;
import com.symphony.bdk.gen.api.model.V4MessageSent;

import lombok.Getter;
import org.apiguardian.api.API;

import javax.annotation.Nonnull;
import java.util.Objects;
import java.util.function.Consumer;

import javax.annotation.Nonnull;

/**
* A "slash" command if the most basic action that can be performed by an end-user through the chat.
*/
Expand Down Expand Up @@ -48,7 +50,7 @@ public static SlashCommand slash(@Nonnull String slashCommandPattern, @Nonnull C
* @throws IllegalArgumentException if command name if empty.
*/
public static SlashCommand slash(@Nonnull String slashCommandPattern, boolean requiresBotMention,
@Nonnull Consumer<CommandContext> callback) {
@Nonnull Consumer<CommandContext> callback) {
return new SlashCommand(slashCommandPattern, requiresBotMention, false, callback, "");
}

Expand All @@ -61,7 +63,7 @@ public static SlashCommand slash(@Nonnull String slashCommandPattern, boolean re
* @return a {@link SlashCommand} instance.
*/
public static SlashCommand slash(@Nonnull String slashCommandPattern, @Nonnull Consumer<CommandContext> callback,
String description) {
String description) {
return slash(slashCommandPattern, true, false, callback, description);
}

Expand All @@ -75,7 +77,7 @@ public static SlashCommand slash(@Nonnull String slashCommandPattern, @Nonnull C
* @return a {@link SlashCommand} instance.
*/
public static SlashCommand slash(@Nonnull String slashCommandPattern, boolean requiresBotMention,
@Nonnull Consumer<CommandContext> callback, String description) {
@Nonnull Consumer<CommandContext> callback, String description) {
return new SlashCommand(slashCommandPattern, requiresBotMention, false, callback, description);
}

Expand All @@ -90,22 +92,22 @@ public static SlashCommand slash(@Nonnull String slashCommandPattern, boolean re
* @return a {@link SlashCommand} instance.
*/
public static SlashCommand slash(@Nonnull String slashCommandPattern, boolean requiresBotMention, boolean isAsync,
@Nonnull Consumer<CommandContext> callback, String description) {
@Nonnull Consumer<CommandContext> callback, String description) {
return new SlashCommand(slashCommandPattern, requiresBotMention, isAsync, callback, description);
}

/**
* Default protected constructor, new instances from static methods only.
*/
protected SlashCommand(@Nonnull String slashCommandPattern, boolean requiresBotMention, boolean isAsync,
@Nonnull Consumer<CommandContext> callback, String description) {
@Nonnull Consumer<CommandContext> callback, String description) {
this.slashCommandName = slashCommandPattern;
this.commandPattern = new SlashCommandPattern(this.slashCommandName);
this.requiresBotMention = requiresBotMention;
this.isAsync = isAsync;
if (this.requiresBotMention) {
this.commandPattern.prependToken(new MatchingUserIdMentionToken(
() -> getBotUserId())); // specific token with no argument name that matches user ID
() -> getBotUserId())); // specific token with no argument name that matches user ID
}

this.callback = callback;
Expand Down Expand Up @@ -137,9 +139,9 @@ public boolean isAsynchronous() {
@Override
protected ActivityInfo info() {
return new ActivityInfo()
.type(ActivityType.COMMAND)
.name(this.slashCommandName)
.description(this.buildCommandDescription());
.type(ActivityType.COMMAND)
.name(this.slashCommandName)
.description(this.buildCommandDescription());
}

@Override
Expand All @@ -149,7 +151,7 @@ protected CommandContext createContextInstance(V4Initiator initiator, V4MessageS

private String buildCommandDescription() {
return this.requiresBotMention ? this.description + " (mention required)"
: this.description + " (mention not required)";
: this.description + " (mention not required)";
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
package com.symphony.bdk.core.activity;

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

import com.symphony.bdk.core.activity.form.TestFormReplyActivity;
import com.symphony.bdk.core.service.datafeed.EventException;
import com.symphony.bdk.core.service.datafeed.EventPayload;
import com.symphony.bdk.gen.api.model.V4Initiator;
import com.symphony.bdk.gen.api.model.V4Stream;
import com.symphony.bdk.gen.api.model.V4SymphonyElementsAction;

import lombok.experimental.Delegate;
import org.junit.jupiter.api.Test;

import java.time.Instant;

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

/**
* Test class for the {@link AbstractActivity}.
*/
Expand All @@ -39,7 +40,7 @@ void shouldFailOnBeforeMatcherError() {
});

assertThrows(EventException.class,
() -> act.processEvent(new V4Initiator(), new V4SymphonyElementsAction().stream(new V4Stream())));
() -> act.processEvent(new V4Initiator(), new V4SymphonyElementsAction().stream(new V4Stream())));
}

@Test
Expand All @@ -63,7 +64,7 @@ void shouldFailOnMatcherError() {
});

assertThrows(EventException.class,
() -> act.processEvent(new V4Initiator(), new V4SymphonyElementsAction()));
() -> act.processEvent(new V4Initiator(), new V4SymphonyElementsAction()));
}

@Test
Expand All @@ -87,7 +88,7 @@ void shouldFailOnActivityExecutionError() {
});

assertThrows(EventException.class,
() -> act.processEvent(new V4Initiator(), new V4SymphonyElementsActionEvent(new V4SymphonyElementsAction())));
() -> act.processEvent(new V4Initiator(), new V4SymphonyElementsActionEvent(new V4SymphonyElementsAction())));
}

static class V4SymphonyElementsActionEvent extends V4SymphonyElementsAction implements EventPayload {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package com.symphony.bdk.core.activity;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import org.junit.jupiter.api.Test;

import java.util.concurrent.ThreadFactory;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class ThreadFactoryBuilderTest {

@Test
Expand All @@ -17,15 +17,15 @@ void builderNameNull() {
@Test
void builderPriorityTooBig() {
assertThatThrownBy(() -> new ThreadFactoryBuilder().setPriority(Thread.MAX_PRIORITY + 1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("Thread priority %s must be <= %s", Thread.MAX_PRIORITY + 1, Thread.MAX_PRIORITY));
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("Thread priority %s must be <= %s", Thread.MAX_PRIORITY + 1, Thread.MAX_PRIORITY));
}

@Test
void builderPriorityTooSmall() {
assertThatThrownBy(() -> new ThreadFactoryBuilder().setPriority(Thread.MIN_PRIORITY - 1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("Thread priority %s must be >= %s", Thread.MIN_PRIORITY - 1, Thread.MIN_PRIORITY));
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("Thread priority %s must be >= %s", Thread.MIN_PRIORITY - 1, Thread.MIN_PRIORITY));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.symphony.bdk.core.activity.command;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.symphony.bdk.core.activity.model.ActivityInfo;
import com.symphony.bdk.core.activity.model.ActivityType;
import com.symphony.bdk.core.activity.parsing.Cashtag;
Expand All @@ -10,6 +14,7 @@
import com.symphony.bdk.gen.api.model.V4Message;
import com.symphony.bdk.gen.api.model.V4MessageSent;
import com.symphony.bdk.gen.api.model.V4Stream;

import org.junit.jupiter.api.Test;

import java.util.Collections;
Expand All @@ -19,10 +24,6 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
* Test class from the {@link SlashCommand}.
*/
Expand Down Expand Up @@ -216,7 +217,8 @@ void testSlashCommandStringMentionCashtagHashtagArguments() {
String cashtagArgName = "cashtagArg";

final SlashCommand cmd = SlashCommand.slash(
slashCommandName + " {" + stringArgName + "} {@" + mentionArgName + "} {#" + hashtagArgName + "} {$" + cashtagArgName + "}",
slashCommandName + " {" + stringArgName + "} {@" + mentionArgName + "} {#" + hashtagArgName + "} {$"
+ cashtagArgName + "}",
handler);
cmd.setBotDisplayName(BOT_DISPLAY_NAME);
cmd.setBotUserId(BOT_USER_ID);
Expand All @@ -230,7 +232,8 @@ void testSlashCommandStringMentionCashtagHashtagArguments() {
+ "<span class=\"entity\" data-entity-id=\"2\">#myhashtag</span> "
+ "<span class=\"entity\" data-entity-id=\"3\">$mycashtag</span>"
+ "</p></div>",
"{\"0\":{\"id\":[{\"type\":\"com.symphony.user.userId\",\"value\":\"" + BOT_USER_ID + "\"}],\"type\":\"com.symphony.user.mention\"},"
"{\"0\":{\"id\":[{\"type\":\"com.symphony.user.userId\",\"value\":\"" + BOT_USER_ID
+ "\"}],\"type\":\"com.symphony.user.mention\"},"
+ "\"1\":{\"id\":[{\"type\":\"com.symphony.user.userId\",\"value\":\"12345679\"}],\"type\":\"com.symphony.user.mention\"},"
+ "\"2\":{\"id\":[{\"type\":\"org.symphonyoss.taxonomy.hashtag\",\"value\":\"myhashtag\"}],\"type\":\"org.symphonyoss.taxonomy\"},"
+ "\"3\":{\"id\":[{\"type\":\"org.symphonyoss.fin.security.id.ticker\",\"value\":\"mycashtag\"}],\"type\":\"org.symphonyoss.fin.security\"}}");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package com.symphony.bdk.examples.activity;

import com.symphony.bdk.core.SymphonyBdk;
import lombok.extern.slf4j.Slf4j;

import static com.symphony.bdk.core.activity.command.SlashCommand.slash;
import static com.symphony.bdk.core.config.BdkConfigLoader.loadFromSymphonyDir;

import com.symphony.bdk.core.SymphonyBdk;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AsyncCommandMain {
public static void main(String[] args) throws Exception {
Expand All @@ -15,8 +16,8 @@ public static void main(String[] args) throws Exception {

bdk.activities().register(slash("/async", true, true, context ->
bdk.messages().send(context.getStreamId(),
"This is an asynchronous command that should not block next commands"),
"Asynchronous command example"
"This is an asynchronous command that should not block next commands"),
"Asynchronous command example"
));

// finally, start the datafeed loop
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ public class GifFormReplyActivity extends FormReplyActivity<GifFormReplyContext>
@Override
public ActivityMatcher<GifFormReplyContext> matcher() {
return context -> "gif-category-form".equals(context.getFormId())
&& "submit".equals(context.getFormValue("action"))
&& StringUtils.isNotEmpty(context.getFormValue("category"));
&& "submit".equals(context.getFormValue("action"))
&& StringUtils.isNotEmpty(context.getFormValue("category"));
}

@Override
Expand All @@ -32,8 +32,8 @@ public boolean isAsynchronous() {
@Override
protected ActivityInfo info() {
return new ActivityInfo()
.type(ActivityType.FORM)
.name("Gif Display category form command")
.description("Form handler for the Gif Category form");
.type(ActivityType.FORM)
.name("Gif Display category form command")
.description("Form handler for the Gif Category form");
}
}

0 comments on commit 4a5a88f

Please sign in to comment.