Created
April 2, 2018 19:28
-
-
Save gastaldi/67c7e7dc50b49aeea8606bebcc627b5b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.fabric8.launcher.web.endpoints; | |
import java.io.IOException; | |
import java.io.PrintWriter; | |
import javax.annotation.PostConstruct; | |
import javax.enterprise.context.RequestScoped; | |
import javax.enterprise.event.Observes; | |
import javax.inject.Inject; | |
import javax.json.Json; | |
import javax.json.JsonArrayBuilder; | |
import javax.json.JsonObjectBuilder; | |
import javax.servlet.http.HttpServletResponse; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import io.fabric8.launcher.core.api.events.StatusEventType; | |
import io.fabric8.launcher.core.api.events.StatusMessageEvent; | |
/** | |
* @author <a href="mailto:[email protected]">George Gastaldi</a> | |
*/ | |
@RequestScoped | |
public class SseOutput { | |
@Inject | |
HttpServletResponse response; | |
private static final ObjectMapper objectMapper = new ObjectMapper(); | |
@PostConstruct | |
public void initialize() throws IOException { | |
JsonArrayBuilder builder = Json.createArrayBuilder(); | |
for (StatusEventType statusEventType : StatusEventType.values()) { | |
JsonObjectBuilder object = Json.createObjectBuilder(); | |
builder.add(object.add(statusEventType.name(), statusEventType.getMessage()).build()); | |
} | |
String payload = builder.build().toString(); | |
send(payload); | |
} | |
private void send(String payload) throws IOException { | |
PrintWriter writer = response.getWriter(); | |
writer.write(payload + "\n\n"); | |
writer.flush(); | |
} | |
/** | |
* Listen to status changes and pushes them to the registered sessions | |
* | |
* @param msg the status message to be send | |
* @throws IOException when message could not be serialized to JSON | |
*/ | |
public void onEvent(@Observes StatusMessageEvent msg) throws IOException { | |
String message = objectMapper.writeValueAsString(msg); | |
send(message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment