private CompletableFuture<Optional<Object>> send(final Event event) { List<MediaType> produces = event.type().<List<MediaType>>map(ImmutableList::of) .orElse(this.produces); SseRenderer ctx = new SseRenderer(renderers, produces, StandardCharsets.UTF_8, locale, locals); return Try.apply(() -> { byte[] bytes = ctx.format(event); return send(event.id(), bytes); }).recover(x -> { CompletableFuture<Optional<Object>> future = new CompletableFuture<>(); future.completeExceptionally(x); return future; }) .get(); }
/** * Send an event and set media type. * * <pre>{@code * sse.send(new MyObject(), "json"); * }</pre> * * <pre>{@code * sse.send(new MyObject(), "json").whenComplete((id, x) -> { * if (x == null) { * handleSuccess(); * } else { * handleError(x); * } * }); * }</pre> * * The <code>id</code> of the success callback correspond to the {@link Event#id()}. * * @param data Event data. * @param type Media type, like: json, xml. * @return A future. The success callback contains the {@link Event#id()}. */ @Nonnull public CompletableFuture<Optional<Object>> send(final Object data, final MediaType type) { return event(data).type(type).send(); }
private CompletableFuture<Optional<Object>> send(final Event event) { List<MediaType> produces = event.type().<List<MediaType>>map(ImmutableList::of) .orElse(this.produces); SseRenderer ctx = new SseRenderer(renderers, produces, StandardCharsets.UTF_8, locale, locals); return Try.apply(() -> { byte[] bytes = ctx.format(event); return send(event.id(), bytes); }).recover(x -> { CompletableFuture<Optional<Object>> future = new CompletableFuture<>(); future.completeExceptionally(x); return future; }) .get(); }
/** * Send an event and set media type. * * <pre>{@code * sse.send(new MyObject(), "json"); * }</pre> * * <pre>{@code * sse.send(new MyObject(), "json").whenComplete((id, x) -> { * if (x == null) { * handleSuccess(); * } else { * handleError(x); * } * }); * }</pre> * * The <code>id</code> of the success callback correspond to the {@link Event#id()}. * * @param data Event data. * @param type Media type, like: json, xml. * @return A future. The success callback contains the {@link Event#id()}. */ @Nonnull public CompletableFuture<Optional<Object>> send(final Object data, final MediaType type) { return event(data).type(type).send(); }
/** * Set event media type. Useful for sengin json, xml, etc.. * * @param type Media Type. * @return This event. */ public Event type(final String type) { return type(MediaType.valueOf(type)); }
/** * Set event media type. Useful for sengin json, xml, etc.. * * @param type Media Type. * @return This event. */ public Event type(final String type) { return type(MediaType.valueOf(type)); }