Skip to content

Commit

Permalink
WIP: websocket communication
Browse files Browse the repository at this point in the history
  • Loading branch information
cc-ju committed Feb 9, 2024
1 parent b1b7b57 commit b84738f
Show file tree
Hide file tree
Showing 10 changed files with 168 additions and 10 deletions.
10 changes: 6 additions & 4 deletions services/streak/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,12 @@ extra["springModulithVersion"] = "1.1.0"
dependencies {
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("org.springframework.boot:spring-boot-starter-data-jdbc")
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
implementation("org.springframework.boot:spring-boot-starter-security")
// implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
// implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-websocket")
// implementation("org.springframework.security:spring-security-messaging")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.flywaydb:flyway-core")
implementation("org.jetbrains.kotlin:kotlin-reflect")
Expand All @@ -83,7 +85,7 @@ dependencies {
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.kafka:spring-kafka-test")
testImplementation("org.springframework.modulith:spring-modulith-starter-test")
testImplementation("org.springframework.security:spring-security-test")
// testImplementation("org.springframework.security:spring-security-test")
testImplementation("io.kotest:kotest-assertions-core:5.8.0")
testImplementation("org.springframework.boot:spring-boot-testcontainers")
testImplementation("org.testcontainers:junit-jupiter")
Expand All @@ -92,7 +94,7 @@ dependencies {
intTestImplementation("org.springframework.kafka:spring-kafka-test")
intTestImplementation("org.springframework.modulith:spring-modulith-starter-test")
intTestImplementation("org.springframework.boot:spring-boot-starter-test")
intTestImplementation("org.springframework.security:spring-security-test")
// intTestImplementation("org.springframework.security:spring-security-test")
intTestImplementation("org.springframework.boot:spring-boot-testcontainers")
intTestImplementation("org.testcontainers:junit-jupiter")
intTestImplementation("org.testcontainers:kafka")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package de.codecentric.habitcentric

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.scheduling.annotation.EnableScheduling

@SpringBootApplication
@EnableScheduling
class StreakApplication

fun main(args: Array<String>) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package de.codecentric.habitcentric.streak.messaging

import org.springframework.context.annotation.Configuration
import org.springframework.messaging.simp.config.MessageBrokerRegistry
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker
import org.springframework.web.socket.config.annotation.StompEndpointRegistry
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer

@Configuration
@EnableWebSocketMessageBroker
//@EnableWebSocketSecurity
class WebSocketConfig : WebSocketMessageBrokerConfigurer {
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
// HTTP URL for WebSocket connection
registry.addEndpoint("/streak-socket").setAllowedOrigins("*")
}

override fun configureMessageBroker(registry: MessageBrokerRegistry) {
// register queue prefix meant for the application
registry.setApplicationDestinationPrefixes("/app")

// Configure spring internal broker to use /topic and /queue as prefix
// There is no special meaning for the broker, it is more like a convention to differentiate
// /topic as pub-sub and /queue as point to point messaging
registry.enableSimpleBroker("/topic", "/queue")
}

// @Bean
// fun configSecurity(messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<*>> {
// messages.simpDestMatchers("/app").permitAll()
//
// return messages.build()
// }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package de.codecentric.habitcentric.streak.messaging

import org.springframework.messaging.Message
import org.springframework.messaging.handler.annotation.MessageMapping
import org.springframework.messaging.handler.annotation.SendTo
import org.springframework.messaging.simp.SimpMessagingTemplate
import org.springframework.messaging.simp.annotation.SubscribeMapping
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Controller
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Controller
class WebSocketController(val simpMessagingTemplate: SimpMessagingTemplate) {

@MessageMapping("/helloApp")
@SendTo("/topic/hello")
fun appMessage(message: Message<String>): String {
return message.payload
}

@SubscribeMapping("/ticker")
fun sub(): String {
return LocalDateTime.now().format(DateTimeFormatter.ISO_TIME);
}

@Scheduled(fixedDelay = 2000)
fun emitTime() {
val time = LocalDateTime.now().format(DateTimeFormatter.ISO_TIME)
simpMessagingTemplate.convertAndSend("/topic/ticker", time);
}
}
6 changes: 5 additions & 1 deletion services/streak/src/main/resources/application.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ spring:

datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:10001}/${DB_NAME:postgres}
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:10005}/${DB_NAME:postgres}
username: ${DB_USER:postgres}
password: ${DB_PASSWORD:postgres}

Expand Down Expand Up @@ -32,5 +32,9 @@ spring:
group-id: streak
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer

management:
tracing:
enabled: false

server:
port: 9005
11 changes: 11 additions & 0 deletions services/ui/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions services/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"@heroicons/react": "1.0.6",
"@icons-pack/react-simple-icons": "9.3.0",
"@popperjs/core": "2.11.8",
"@stomp/stompjs": "^7.0.0",
"@tailwindcss/forms": "0.5.7",
"@types/node": "20.11.16",
"@types/react": "18.2.52",
Expand Down
2 changes: 2 additions & 0 deletions services/ui/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { AuthProvider } from "react-oidc-context";
import { oidc } from "./auth/config/oidc";
import { Route, Routes } from "react-router-dom";
import RequireAuthWhenOidcIsEnabled from "./auth/RequireAuthWhenOidcIsEnabled";
import Socket from "./Socket";

function App() {
return (
Expand All @@ -16,6 +17,7 @@ function App() {

<Routes>
<Route path="/" element={<LandingPage />} />
<Route path="/ws" element={<Socket />} />
<Route
path="/overview"
element={
Expand Down
70 changes: 70 additions & 0 deletions services/ui/src/Socket.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { useEffect, useState } from "react";
import { ActivationState, Client } from "@stomp/stompjs";

function Socket() {
const [wsOutput, setWsOutput] = useState("");

useEffect(() => {
// let accessToken = auth.user?.access_token || "";
// console.log(auth);
// console.log("Token", accessToken);

const client = new Client({
brokerURL: "ws://localhost:9005/streak-socket",
// connectHeaders: {
// Authentication: accessToken,
// },
onWebSocketError: (e) => {
console.log("ws error:", e);
},
onWebSocketClose: (e) => {
console.log("ws close:", e);
},
debug: (str) => {
console.log("debug:", str);
},
onConnect: () => {
client.subscribe("/app/ticker", (message) =>
console.log(`Received app ticker: ${message.body}`)
);
client.subscribe("/topic/ticker", (message) =>
console.log(`Received ticker: ${message.body}`)
);
client.subscribe("/topic/hello", (message) =>
console.log(`Received hello: ${message.body}`)
);

client.publish({
destination: "/app/helloApp",
body: "Hi from stomp!",
});

// client.publish({ destination: "/topic/test01", body: "First Message" });
},
onStompError: (frame) => {
console.log("Broker reported error: " + frame.headers["message"]);
console.log("Additional details: " + frame.body);
},
onChangeState: (s) => {
ActivationState;
console.log("connection state: ", s);
},
});
client.activate();
setWsOutput("hi!");

// client.subscribe("/topic", (message) => {
// setWsOutput(message.body);
// });
//
return () => {
console.trace();
console.log("destroy?");
client.deactivate();
};
}, []);

return <pre>{wsOutput}</pre>;
}

export default Socket;
10 changes: 5 additions & 5 deletions services/ui/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ enableMsw().then(() => {
const container = document.getElementById("root");
const root = createRoot(container!);
root.render(
<React.StrictMode>
<BrowserRouter basename={import.meta.env.BASE_URL}>
<App />
</BrowserRouter>
</React.StrictMode>
// <React.StrictMode>
<BrowserRouter basename={import.meta.env.BASE_URL}>
<App />
</BrowserRouter>
// </React.StrictMode>
);
});

Expand Down

0 comments on commit b84738f

Please sign in to comment.