Managers now have changeable eventbus

This commit is contained in:
lieght
2025-12-06 21:14:58 +01:00
parent ea82ccae45
commit 4ef0d53d3c
9 changed files with 59 additions and 64 deletions

View File

@@ -6,25 +6,29 @@ import org.toop.framework.audio.interfaces.SoundEffectManager;
import org.toop.framework.audio.interfaces.VolumeManager;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.eventbus.GlobalEventBus;
import org.toop.framework.eventbus.bus.EventBus;
import org.toop.framework.resource.types.AudioResource;
public class AudioEventListener<T extends AudioResource, K extends AudioResource> {
private final EventBus eventBus;
private final MusicManager<T> musicManager;
private final SoundEffectManager<K> soundEffectManager;
private final VolumeManager audioVolumeManager;
public AudioEventListener(
EventBus eventBus,
MusicManager<T> musicManager,
SoundEffectManager<K> soundEffectManager,
VolumeManager audioVolumeManager
) {
this.eventBus = eventBus;
this.musicManager = musicManager;
this.soundEffectManager = soundEffectManager;
this.audioVolumeManager = audioVolumeManager;
}
public AudioEventListener<?, ?> initListeners(String buttonSoundToPlay) {
new EventFlow()
new EventFlow(eventBus)
.listen(AudioEvents.StopAudioManager.class, this::handleStopMusicManager, false)
.listen(AudioEvents.PlayEffect.class, this::handlePlaySound, false)
.listen(AudioEvents.SkipMusic.class, this::handleSkipSong, false)

View File

@@ -6,7 +6,7 @@ import org.toop.framework.audio.events.AudioEvents;
import org.toop.framework.dispatch.interfaces.Dispatcher;
import org.toop.framework.dispatch.JavaFXDispatcher;
import org.toop.annotations.TestsOnly;
import org.toop.framework.eventbus.GlobalEventBus;
import org.toop.framework.eventbus.bus.EventBus;
import org.toop.framework.resource.types.AudioResource;
import java.util.*;
@@ -17,6 +17,7 @@ import java.util.concurrent.TimeUnit;
public class MusicManager<T extends AudioResource> implements org.toop.framework.audio.interfaces.MusicManager<T> {
private static final Logger logger = LogManager.getLogger(MusicManager.class);
private final EventBus eventBus;
private final List<T> backgroundMusic = new ArrayList<>();
private final Dispatcher dispatcher;
private final List<T> resources;
@@ -26,7 +27,8 @@ public class MusicManager<T extends AudioResource> implements org.toop.framework
private ScheduledExecutorService scheduler;
public MusicManager(List<T> resources, boolean shuffleMusic) {
public MusicManager(EventBus eventbus, List<T> resources, boolean shuffleMusic) {
this.eventBus = eventbus;
this.dispatcher = new JavaFXDispatcher();
this.resources = resources;
// Shuffle if wanting to shuffle
@@ -39,7 +41,8 @@ public class MusicManager<T extends AudioResource> implements org.toop.framework
* {@code @TestsOnly} DO NOT USE
*/
@TestsOnly
public MusicManager(List<T> resources, Dispatcher dispatcher) {
public MusicManager(EventBus eventBus, List<T> resources, Dispatcher dispatcher) {
this.eventBus = eventBus;
this.dispatcher = dispatcher;
this.resources = new ArrayList<>(resources);
backgroundMusic.addAll(resources);
@@ -123,7 +126,7 @@ public class MusicManager<T extends AudioResource> implements org.toop.framework
Runnable currentMusicTask = new Runnable() {
@Override
public void run() {
GlobalEventBus.get().post(new AudioEvents.PlayingMusic(track.getName(), track.currentPosition(), track.duration()));
eventBus.post(new AudioEvents.PlayingMusic(track.getName(), track.currentPosition(), track.duration()));
scheduler.schedule(this, 1, TimeUnit.SECONDS);
}
};

View File

@@ -2,18 +2,10 @@ package org.toop.framework.audio;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.resource.ResourceManager;
import org.toop.framework.resource.ResourceMeta;
import org.toop.framework.resource.resources.BaseResource;
import org.toop.framework.resource.resources.MusicAsset;
import org.toop.framework.resource.resources.SoundEffectAsset;
import org.toop.framework.resource.types.AudioResource;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

View File

@@ -4,19 +4,20 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.SnowflakeGenerator;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.eventbus.bus.EventBus;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.framework.networking.exceptions.ClientNotFoundException;
import org.toop.framework.networking.interfaces.NetworkingClientManager;
public class NetworkingClientEventListener {
private static final Logger logger = LogManager.getLogger(NetworkingClientEventListener.class);
private final NetworkingClientManager clientManager;
/** Starts a connection manager, to manage, connections. */
public NetworkingClientEventListener(NetworkingClientManager clientManager) {
public NetworkingClientEventListener(EventBus eventBus, NetworkingClientManager clientManager) {
this.clientManager = clientManager;
new EventFlow()
new EventFlow(eventBus)
.listen(NetworkEvents.StartClient.class, this::handleStartClient, false)
.listen(NetworkEvents.SendCommand.class, this::handleCommand, false)
.listen(NetworkEvents.SendLogin.class, this::handleSendLogin, false)

View File

@@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.eventbus.GlobalEventBus;
import org.toop.framework.eventbus.bus.EventBus;
import org.toop.framework.networking.events.NetworkEvents;
import org.toop.framework.networking.exceptions.ClientNotFoundException;
import org.toop.framework.networking.exceptions.CouldNotConnectException;
@@ -18,9 +18,13 @@ import org.toop.framework.networking.types.NetworkingConnector;
public class NetworkingClientManager implements org.toop.framework.networking.interfaces.NetworkingClientManager {
private static final Logger logger = LogManager.getLogger(NetworkingClientManager.class);
private final EventBus eventBus;
private final Map<Long, NetworkingClient> networkClients = new ConcurrentHashMap<>();
public NetworkingClientManager() {}
public NetworkingClientManager(EventBus eventBus) {
this.eventBus = eventBus;
}
private void connectHelper(
long id,
@@ -55,7 +59,7 @@ public class NetworkingClientManager implements org.toop.framework.networking.in
nClient.connect(id, nConnector.host(), nConnector.port());
networkClients.put(id, nClient);
logger.info("New client started successfully for {}:{}", nConnector.host(), nConnector.port());
GlobalEventBus.get().post(new NetworkEvents.ConnectTry(id, attempts, nConnector.reconnectAttempts(), true));
eventBus.post(new NetworkEvents.ConnectTry(id, attempts, nConnector.reconnectAttempts(), true));
onSuccess.run();
scheduler.shutdown();
} catch (CouldNotConnectException e) {
@@ -63,17 +67,17 @@ public class NetworkingClientManager implements org.toop.framework.networking.in
if (attempts < nConnector.reconnectAttempts()) {
logger.warn("Could not connect to {}:{}. Retrying in {} {}",
nConnector.host(), nConnector.port(), nConnector.timeout(), nConnector.timeUnit());
GlobalEventBus.get().post(new NetworkEvents.ConnectTry(id, attempts, nConnector.reconnectAttempts(), false));
eventBus.post(new NetworkEvents.ConnectTry(id, attempts, nConnector.reconnectAttempts(), false));
scheduler.schedule(this, nConnector.timeout(), nConnector.timeUnit());
} else {
logger.error("Failed to start client for {}:{} after {} attempts", nConnector.host(), nConnector.port(), attempts);
GlobalEventBus.get().post(new NetworkEvents.ConnectTry(id, -1, nConnector.reconnectAttempts(), false));
eventBus.post(new NetworkEvents.ConnectTry(id, -1, nConnector.reconnectAttempts(), false));
onFailure.run();
scheduler.shutdown();
}
} catch (Exception e) {
logger.error("Unexpected exception during startClient", e);
GlobalEventBus.get().post(new NetworkEvents.ConnectTry(id, -1, nConnector.reconnectAttempts(), false));
eventBus.post(new NetworkEvents.ConnectTry(id, -1, nConnector.reconnectAttempts(), false));
onFailure.run();
scheduler.shutdown();
}

View File

@@ -11,6 +11,7 @@ import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.eventbus.bus.EventBus;
import org.toop.framework.networking.exceptions.CouldNotConnectException;
import org.toop.framework.networking.handlers.NetworkingGameClientHandler;
import org.toop.framework.networking.interfaces.NetworkingClient;
@@ -19,9 +20,13 @@ import java.net.InetSocketAddress;
public class TournamentNetworkingClient implements NetworkingClient {
private static final Logger logger = LogManager.getLogger(TournamentNetworkingClient.class);
private final EventBus eventBus;
private Channel channel;
public TournamentNetworkingClient() {}
public TournamentNetworkingClient(EventBus eventBus) {
this.eventBus = eventBus;
}
@Override
public InetSocketAddress getAddress() {
@@ -40,7 +45,7 @@ public class TournamentNetworkingClient implements NetworkingClient {
new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
NetworkingGameClientHandler handler = new NetworkingGameClientHandler(clientId);
NetworkingGameClientHandler handler = new NetworkingGameClientHandler(eventBus, clientId);
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LineBasedFrameDecoder(1024)); // split at \n

View File

@@ -8,15 +8,17 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.framework.eventbus.EventFlow;
import org.toop.framework.eventbus.bus.EventBus;
import org.toop.framework.networking.events.NetworkEvents;
public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LogManager.getLogger(NetworkingGameClientHandler.class);
private final EventBus eventBus;
private final long connectionId;
public NetworkingGameClientHandler(long connectionId) {
public NetworkingGameClientHandler(EventBus eventBus, long connectionId) {
this.eventBus = eventBus;
this.connectionId = connectionId;
}
@@ -40,9 +42,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
"Received SVR message from server-{}, data: {}",
ctx.channel().remoteAddress(),
msg);
new EventFlow()
.addPostEvent(new NetworkEvents.ServerResponse(this.connectionId))
.asyncPostEvent();
eventBus.post(new NetworkEvents.ServerResponse(this.connectionId));
parseServerReturn(rec);
return;
}
@@ -113,11 +113,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
.map(m -> m.group(1).trim())
.toArray(String[]::new);
new EventFlow()
.addPostEvent(
new NetworkEvents.GameMoveResponse(
this.connectionId, msg[0], msg[1], msg[2]))
.asyncPostEvent();
eventBus.post(new NetworkEvents.GameMoveResponse(this.connectionId, msg[0], msg[1], msg[2]));
}
private void gameWinConditionHandler(String rec) {
@@ -128,9 +124,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
.findFirst()
.orElse("");
new EventFlow()
.addPostEvent(new NetworkEvents.GameResultResponse(this.connectionId, condition))
.asyncPostEvent();
eventBus.post(new NetworkEvents.GameResultResponse(this.connectionId, condition));
}
private void gameChallengeHandler(String rec) {
@@ -145,17 +139,9 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
.toArray(String[]::new);
if (isCancelled)
new EventFlow()
.addPostEvent(
new NetworkEvents.ChallengeCancelledResponse(
this.connectionId, msg[0]))
.asyncPostEvent();
eventBus.post(new NetworkEvents.GameResultResponse(this.connectionId, msg[0]));
else
new EventFlow()
.addPostEvent(
new NetworkEvents.ChallengeResponse(
this.connectionId, msg[0], msg[1], msg[2]))
.asyncPostEvent();
eventBus.post(new NetworkEvents.ChallengeResponse(this.connectionId, msg[0], msg[1], msg[2]));
} catch (ArrayIndexOutOfBoundsException e) {
logger.error("Array out of bounds for: {}", rec, e);
}
@@ -171,11 +157,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
.toArray(String[]::new);
// [0] playerToMove, [1] gameType, [2] opponent
new EventFlow()
.addPostEvent(
new NetworkEvents.GameMatchResponse(
this.connectionId, msg[0], msg[1], msg[2]))
.asyncPostEvent();
eventBus.post(new NetworkEvents.GameMatchResponse(this.connectionId, msg[0], msg[1], msg[2]));
} catch (ArrayIndexOutOfBoundsException e) {
logger.error("Array out of bounds for: {}", rec, e);
}
@@ -190,9 +172,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
.toString()
.trim();
new EventFlow()
.addPostEvent(new NetworkEvents.YourTurnResponse(this.connectionId, msg))
.asyncPostEvent();
eventBus.post(new NetworkEvents.YourTurnResponse(this.connectionId, msg));
}
private void playerlistHandler(String rec) {
@@ -203,9 +183,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
.map(m -> m.group(1).trim())
.toArray(String[]::new);
new EventFlow()
.addPostEvent(new NetworkEvents.PlayerlistResponse(this.connectionId, players))
.asyncPostEvent();
eventBus.post(new NetworkEvents.PlayerlistResponse(this.connectionId, players));
}
private void gamelistHandler(String rec) {
@@ -216,9 +194,7 @@ public class NetworkingGameClientHandler extends ChannelInboundHandlerAdapter {
.map(m -> m.group(1).trim())
.toArray(String[]::new);
new EventFlow()
.addPostEvent(new NetworkEvents.GamelistResponse(this.connectionId, gameTypes))
.asyncPostEvent();
eventBus.post(new NetworkEvents.GamelistResponse(this.connectionId, gameTypes));
}
private void helpHandler(String rec) {