private static T convertServerSentEvent()

in server/src/main/java/com/epam/aidial/core/server/service/ApplicationOperatorService.java [188:222]


    private static <T> T convertServerSentEvent(String body, Class<T> clazz) {
        StringTokenizer tokenizer = new StringTokenizer(body, "\n");

        while (tokenizer.hasMoreTokens()) {
            String line = tokenizer.nextToken().trim();
            if (line.isBlank() || line.startsWith(":")) {
                continue; // empty or comment
            }

            if (!line.startsWith("event:")) {
                throw new IllegalStateException("Invalid response. Invalid line: " + line);
            }

            if (!tokenizer.hasMoreTokens()) {
                throw new IllegalStateException("Invalid response. No line: \"data:\"" + line);
            }

            String event = line.substring("event:".length()).trim();
            line = tokenizer.nextToken().trim();
            String data = line.substring("data:".length()).trim();

            if (event.equals("result")) {
                return ProxyUtil.convertToObject(data, clazz);
            }

            if (event.equals("error")) {
                ErrorResponse error = ProxyUtil.convertToObject(data, ErrorResponse.class);
                throw new IllegalStateException(error == null ? "Unknown error" : error.message());
            }

            throw new IllegalStateException("Invalid response. Invalid event: " + event);
        }

        throw new IllegalStateException("Invalid response. Unexpected end of stream");
    }