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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,34 @@ public class NostrSpringWebSocketClient implements NostrIF {
@Getter
private Identity sender;

private static NostrSpringWebSocketClient INSTANCE;
private static volatile NostrSpringWebSocketClient INSTANCE;

public NostrSpringWebSocketClient(String relayName, String relayUri) {
setRelays(Map.of(relayName, relayUri));
}

public static NostrIF getInstance() {
return (INSTANCE == null) ? new NostrSpringWebSocketClient() : INSTANCE;
if (INSTANCE == null) {
synchronized (NostrSpringWebSocketClient.class) {
if (INSTANCE == null) {
INSTANCE = new NostrSpringWebSocketClient();
}
}
}
return INSTANCE;
}

public static NostrIF getInstance(@NonNull Identity sender) {
return (INSTANCE == null) ? new NostrSpringWebSocketClient(sender) : INSTANCE;
if (INSTANCE == null) {
synchronized (NostrSpringWebSocketClient.class) {
if (INSTANCE == null) {
INSTANCE = new NostrSpringWebSocketClient(sender);
Comment thread
tcheeric marked this conversation as resolved.
} else if (INSTANCE.getSender() == null) {
INSTANCE.sender = sender; // Initialize sender if not already set
}
}
}
return INSTANCE;
}

public NostrSpringWebSocketClient(@NonNull Identity sender) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package nostr.api.unit;

import nostr.api.NostrIF;
import nostr.api.NostrSpringWebSocketClient;
import nostr.id.Identity;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;

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

public class NostrSpringWebSocketClientTest {

@BeforeEach
void resetSingleton() throws Exception {
Field instance = NostrSpringWebSocketClient.class.getDeclaredField("INSTANCE");
instance.setAccessible(true);
instance.set(null, null);
}

@Test
void getInstanceShouldReturnSameInstance() {
NostrIF first = NostrSpringWebSocketClient.getInstance();
NostrIF second = NostrSpringWebSocketClient.getInstance();
assertSame(first, second, "Multiple calls should return the same instance");
}

@Test
void getInstanceWithIdentityShouldReturnSameInstance() {
Identity identity = Identity.generateRandomIdentity();
NostrIF first = NostrSpringWebSocketClient.getInstance(identity);
NostrIF second = NostrSpringWebSocketClient.getInstance();
assertSame(first, second, "Calls with and without identity should return the same instance");
}
}