io.cloudevents.v1.CloudEventBuilder Java Examples

The following examples show how to use io.cloudevents.v1.CloudEventBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RSocketServicesPublishHook.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(@NotNull ApplicationReadyEvent applicationReadyEvent) {
    UpstreamCluster brokerCluster = upstreamManager.findBroker();
    if (brokerCluster == null) return;
    //rsocket broker cluster logic
    CloudEventImpl<AppStatusEvent> appStatusEventCloudEvent = CloudEventBuilder.<AppStatusEvent>builder()
            .withId(UUID.randomUUID().toString())
            .withTime(ZonedDateTime.now())
            .withSource(URI.create("app://" + RSocketAppContext.ID))
            .withType(AppStatusEvent.class.getCanonicalName())
            .withDataContentType(WellKnownMimeType.APPLICATION_JSON.getString())
            .withData(new AppStatusEvent(RSocketAppContext.ID, AppStatusEvent.STATUS_SERVING))
            .build();
    LoadBalancedRSocket loadBalancedRSocket = brokerCluster.getLoadBalancedRSocket();
    String brokers = String.join(",", loadBalancedRSocket.getActiveSockets().keySet());
    loadBalancedRSocket.fireCloudEventToUpstreamAll(appStatusEventCloudEvent)
            .doOnSuccess(aVoid -> log.info(RsocketErrorCode.message("RST-301200", brokers)))
            .subscribe();
    CloudEventImpl<ServicesExposedEvent> servicesExposedEventCloudEvent = rsocketRequesterSupport.servicesExposedEvent().get();
    if (servicesExposedEventCloudEvent != null) {
        loadBalancedRSocket.fireCloudEventToUpstreamAll(servicesExposedEventCloudEvent).doOnSuccess(aVoid -> {
            String exposedServices = rsocketRequesterSupport.exposedServices().get().stream().map(ServiceLocator::getGsv).collect(Collectors.joining(","));
            log.info(RsocketErrorCode.message("RST-301201", exposedServices, brokers));
        }).subscribe();
    }
}
 
Example #2
Source File: JsonSchemaPreProcessorTest.java    From liiklus with MIT License 6 votes vote down vote up
@Test
void testCloudEventWithWrongMimeType() {
    var processor = getProcessor();

    assertThatThrownBy(() -> {
        preProcess(processor,
                CloudEventBuilder.builder()
                        .withId(UUID.randomUUID().toString())
                        .withType("com.example.cloudevent")
                        .withSource(URI.create("/tests"))
                        .withDataContentType("text/plain")
                        .withData(
                                JsonSchemaPreProcessor.JSON_MAPPER.writeValueAsBytes(
                                        Map.of("foo", 123)
                                )
                        )
                        .build()
        );
    }).hasMessageContaining("Media type isn't compatible with 'application/json'");
}
 
Example #3
Source File: JsonSchemaPreProcessorTest.java    From liiklus with MIT License 6 votes vote down vote up
@Test
void testCloudEventWithCompatibleMediaType() {
    var processor = getProcessor();

    assertThatThrownBy(() -> {
        preProcess(processor,
                CloudEventBuilder.builder()
                        .withId(UUID.randomUUID().toString())
                        .withType("com.example.cloudevent")
                        .withSource(URI.create("/tests"))
                        .withDataContentType("application/json;v2")
                        .withData(
                                JsonSchemaPreProcessor.JSON_MAPPER.writeValueAsBytes(
                                        Map.of("foo", 123)
                                )
                        )
                        .build()
        );
    }).hasMessageContaining("$.foo: integer found, string expected");
}
 
Example #4
Source File: CloudEventMessageBuilder.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Override
public CloudEventMessage<T> build(T data, AttributesImpl attributes,
        Collection<ExtensionFormat> extensions) {
    CloudEventBuilder<T> builder = CloudEventBuilder.<T> builder()
            .withId(attributes.getId())
            .withSource(attributes.getSource())
            .withType(attributes.getType());

    attributes.getTime().ifPresent(builder::withTime);
    attributes.getDataschema().ifPresent(builder::withDataschema);
    attributes.getDatacontenttype().ifPresent(builder::withDataContentType);
    attributes.getSubject().ifPresent(builder::withSubject);
    extensions.forEach(builder::withExtension);

    CloudEventImpl<T> event = builder
            .withData(data)
            .build();

    return new DefaultCloudEventMessage<>(event);
}
 
Example #5
Source File: DefaultAggregator.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private static CloudEventImpl<TraceEvent> buildNotEnoughDataCloudEvent(DMNModel model, String executionId) {
    TraceHeader header = new TraceHeader(
            TraceEventType.DMN,
            executionId,
            null,
            null,
            null,
            TraceResourceId.from(model),
            Stream.of(
                    Message.from(InternalMessageType.NOT_ENOUGH_DATA),
                    model == null ? Message.from(InternalMessageType.DMN_MODEL_NOT_FOUND) : null
            ).filter(Objects::nonNull).collect(Collectors.toList())
    );

    TraceEvent event = new TraceEvent(header, Collections.emptyList(), Collections.emptyList(), Collections.emptyList());

    return CloudEventBuilder.<TraceEvent>builder()
            .withType(TraceEvent.class.getName())
            .withId(executionId)
            .withSource(URI.create(URLEncoder.encode(UNKNOWN_SOURCE_URL, StandardCharsets.UTF_8)))
            .withData(event)
            .build();
}
 
Example #6
Source File: CloudEventTest.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloudEvent() throws Exception {
    UpstreamClusterChangedEvent upstreamClusterChangedEvent = new UpstreamClusterChangedEvent();
    upstreamClusterChangedEvent.setGroup("demo");
    upstreamClusterChangedEvent.setInterfaceName("com.alibaba.account.AccountService");
    upstreamClusterChangedEvent.setVersion("1.0.0");
    upstreamClusterChangedEvent.setUris(Arrays.asList("demo1", "demo2"));
    // passing in the given attributes
    final CloudEventImpl<UpstreamClusterChangedEvent> cloudEvent = CloudEventBuilder.<UpstreamClusterChangedEvent>builder()
            .withType("com.alibaba.rsocket.upstream.UpstreamClusterChangedEvent")
            .withId("xxxxx")
            .withTime(ZonedDateTime.now())
            .withDataschema(URI.create("demo:demo"))
            .withDataContentType("application/json")
            .withSource(new URI("demo"))
            .withData(upstreamClusterChangedEvent)
            .build();
    String text = Json.encode(cloudEvent);
    CloudEventImpl<UpstreamClusterChangedEvent> event2 = Json.decodeValue(text, new TypeReference<CloudEventImpl<UpstreamClusterChangedEvent>>() {
    });
    UpstreamClusterChangedEvent upstreamClusterChangedEvent1 = CloudEventSupport.unwrapData(event2, UpstreamClusterChangedEvent.class);
    System.out.println(Json.encode(upstreamClusterChangedEvent1));
    Assertions.assertEquals(upstreamClusterChangedEvent.getInterfaceName(), upstreamClusterChangedEvent1.getInterfaceName());
}
 
Example #7
Source File: CloudEventTest.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Test
public void testJson() throws Exception {
    // given
    final String eventId = UUID.randomUUID().toString();
    final URI src = URI.create("/trigger");
    final String eventType = "My.Cloud.Event.Type";

    // passing in the given attributes
    final CloudEventImpl<String> cloudEvent = CloudEventBuilder.<String>builder()
            .withType(eventType)
            .withId(eventId)
            .withTime(ZonedDateTime.now())
            .withDataschema(URI.create("demo:demo"))
            .withDataContentType("text/plain")
            .withSource(src)
            .withData("欢迎")
            .build();
    String text = Json.encode(cloudEvent);
    System.out.println(text);
    text = text.replace("欢迎", "leijuan");
    Json.decodeValue(text, new TypeReference<CloudEventImpl<String>>() {
    });
    System.out.println(cloudEvent.getData().get());
}
 
Example #8
Source File: RSocketCompositeMetadataTest.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Test
public void testCloudEvents() throws Exception {
    final CloudEventImpl<String> cloudEvent = CloudEventBuilder.<String>builder()
            .withType("eventType")
            .withId("xxxx")
            .withTime(ZonedDateTime.now())
            .withDataschema(URI.create("demo:demo"))
            .withDataContentType("text/plain")
            .withSource(URI.create("app://app1"))
            .withData("欢迎")
            .build();
    Payload payload = cloudEventToPayload(cloudEvent);
    payload.getMetadata().rewind();
    RSocketCompositeMetadata compositeMetadata = RSocketCompositeMetadata.from(payload.metadata());
    MessageMimeTypeMetadata dataEncodingMetadata = compositeMetadata.getDataEncodingMetadata();
    Assertions.assertNotNull(dataEncodingMetadata);
    System.out.println(dataEncodingMetadata.getMimeType());
}
 
Example #9
Source File: RSocketBrokerManagerGossipImplTest.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Test
public void testGossipMessageWithCloudEvents() throws Exception {
    AppStatusEvent appStatusEvent = new AppStatusEvent("1", 1);
    CloudEventImpl<AppStatusEvent> cloudEvent = CloudEventBuilder.<AppStatusEvent>builder()
            .withId("1")
            .withSource(URI.create("app://1"))
            .withType("type1")
            .withTime(ZonedDateTime.now())
            .withDataContentType("application/json")
            .withData(appStatusEvent)
            .withSubject("app status update")
            .build();
    Message message = Message.builder().correlationId("1").data(cloudEvent).build();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    messageCodec.serialize(message, bos);
    Message message1 = messageCodec.deserialize(new ByteArrayInputStream(bos.toByteArray()));
    CloudEventImpl<AppStatusEvent> cloudEvent2 = message1.data();
    Assertions.assertThat(cloudEvent2.getData()).isPresent();
}
 
Example #10
Source File: AppStatusCloudEventProcessor.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
private void registerConfigPush(AppMetadata appMetadata) {
    String appName = appMetadata.getName();
    if (!listeners.containsKey(appName)) {
        listeners.put(appName, configurationService.watch(appName).subscribe(config -> {
            CloudEventImpl<ConfigEvent> configEvent = CloudEventBuilder.<ConfigEvent>builder()
                    .withId(UUID.randomUUID().toString())
                    .withTime(ZonedDateTime.now())
                    .withSource(URI.create("broker://" + RSocketAppContext.ID))
                    .withType(ConfigEvent.class.getCanonicalName())
                    .withDataContentType("text/x-java-properties")
                    .withData(new ConfigEvent(appName, "text/x-java-properties", config))
                    .build();
            rsocketBrokerHandlerRegistry.broadcast(appName, configEvent).subscribe();
        }));
    }
}
 
Example #11
Source File: OpsController.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@PostMapping("/upstream/update")
public String updateUpstream(@RequestBody String uris) throws Exception {
    UpstreamClusterChangedEvent upstreamClusterChangedEvent = new UpstreamClusterChangedEvent();
    upstreamClusterChangedEvent.setGroup("");
    upstreamClusterChangedEvent.setInterfaceName("*");
    upstreamClusterChangedEvent.setVersion("");
    upstreamClusterChangedEvent.setUris(Arrays.asList(uris.split(",")));

    // passing in the given attributes
    final CloudEventImpl<UpstreamClusterChangedEvent> cloudEvent = CloudEventBuilder.<UpstreamClusterChangedEvent>builder()
            .withType("com.alibaba.rsocket.upstream.UpstreamClusterChangedEvent")
            .withId(UUID.randomUUID().toString())
            .withTime(ZonedDateTime.now())
            .withDataschema(URI.create("rsocket:event"))
            .withDataContentType("application/json")
            .withSource(new URI("app://" + RSocketAppContext.ID))
            .withData(upstreamClusterChangedEvent)
            .build();
    eventProcessor.onNext(cloudEvent);
    return "success";
}
 
Example #12
Source File: ConfigController.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@PostMapping("/refresh/{appName}")
public Mono<String> refresh(@PathVariable(name = "appName") String appName,
                            @RequestParam(name = "ip", required = false) String ip,
                            @RequestParam(name = "id", required = false) String id,
                            @RequestHeader(name = HttpHeaders.AUTHORIZATION) String jwtToken,
                            @RequestBody String body) {
    RSocketAppPrincipal appPrincipal = parseAppPrincipal(jwtToken);
    if (appPrincipal != null && appPrincipal.getSubject().equalsIgnoreCase("rsocket-admin")) {
        //update config for ip or id
        if (ip != null || id != null) {
            CloudEventImpl<ConfigEvent> configEvent = CloudEventBuilder.<ConfigEvent>builder()
                    .withId(UUID.randomUUID().toString())
                    .withTime(ZonedDateTime.now())
                    .withSource(URI.create("broker://" + RSocketAppContext.ID))
                    .withType(ConfigEvent.class.getCanonicalName())
                    .withDataContentType("text/x-java-properties")
                    .withData(new ConfigEvent(appName, "text/x-java-properties", body))
                    .build();
            return Flux.fromIterable(handlerRegistry.findByAppName(appName)).filter(handler -> {
                AppMetadata appMetadata = handler.getAppMetadata();
                return appMetadata.getUuid().equals(id) || appMetadata.getIp().equals(ip);
            }).flatMap(handler -> handler.fireCloudEventToPeer(configEvent)).then(Mono.just("success"));
        } else {
            return configurationService.put(appName + ":application.properties", body).map(aVoid -> "success");
        }
    } else {
        return Mono.error(new InvalidException(RsocketErrorCode.message("RST-500403")));
    }
}
 
Example #13
Source File: BroadcastSpread.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
default CloudEventImpl<Map<String, Object>> buildMapCloudEvent(@NotNull String type, @NotNull String subject, @NotNull Map<String, Object> data) {
    return CloudEventBuilder.<Map<String, Object>>builder()
            .withId(UUID.randomUUID().toString())
            .withSource(URI.create("broker://" + RSocketAppContext.ID))
            .withType(type)
            .withTime(ZonedDateTime.now())
            .withDataContentType("application/json")
            .withData(data)
            .withSubject(subject)
            .build();
}
 
Example #14
Source File: CloudEventSupport.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
default CloudEventImpl<T> toCloudEvent(URI source) {
    CloudEventBuilder<T> builder = CloudEventBuilder.builder();
    builder.withId(UUID.randomUUID().toString());
    builder.withType(this.getClass().getCanonicalName());
    builder.withDataContentType(RSocketMimeType.CloudEventsJson.getType());
    builder.withSource(source);
    builder.withTime(ZonedDateTime.now());
    builder.withData((T) this);
    return builder.build();
}
 
Example #15
Source File: RSocketBrokerHandlerRegistryImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
private CloudEventImpl<UpstreamClusterChangedEvent> getBrokerClustersEvent(Collection<RSocketBroker> rSocketBrokers, String topology) {
    List<String> uris;
    if ("internet".equals(topology)) {
        uris = rSocketBrokers.stream()
                .filter(rsocketBroker -> rsocketBroker.isActive() && rsocketBroker.getExternalDomain() != null)
                .map(RSocketBroker::getAliasUrl)
                .collect(Collectors.toList());
    } else {
        uris = rSocketBrokers.stream()
                .filter(RSocketBroker::isActive)
                .map(RSocketBroker::getUrl)
                .collect(Collectors.toList());
    }
    UpstreamClusterChangedEvent upstreamClusterChangedEvent = new UpstreamClusterChangedEvent();
    upstreamClusterChangedEvent.setGroup("");
    upstreamClusterChangedEvent.setInterfaceName("*");
    upstreamClusterChangedEvent.setVersion("");
    upstreamClusterChangedEvent.setUris(uris);

    // passing in the given attributes
    return CloudEventBuilder.<UpstreamClusterChangedEvent>builder()
            .withType("com.alibaba.rsocket.upstream.UpstreamClusterChangedEvent")
            .withId(UUID.randomUUID().toString())
            .withTime(ZonedDateTime.now())
            .withDataschema(URI.create("rsocket:event:com.alibaba.rsocket.upstream.UpstreamClusterChangedEvent"))
            .withDataContentType(WellKnownMimeType.APPLICATION_JSON.getString())
            .withSource(URI.create("broker://" + RSocketAppContext.ID))
            .withData(upstreamClusterChangedEvent)
            .build();
}
 
Example #16
Source File: RSocketBrokerHandlerRegistryImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
private CloudEventImpl<AppStatusEvent> appStatusEventCloudEvent(AppMetadata appMetadata, Integer status) {
    return CloudEventBuilder.<AppStatusEvent>builder()
            .withId(UUID.randomUUID().toString())
            .withTime(ZonedDateTime.now())
            .withSource(URI.create("app://" + appMetadata.getUuid()))
            .withType(AppStatusEvent.class.getCanonicalName())
            .withDataContentType("application/json")
            .withData(new AppStatusEvent(appMetadata.getUuid(), status))
            .build();
}
 
Example #17
Source File: OpsRestController.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
private CloudEventImpl<UpstreamClusterChangedEvent> getUpstreamClusterChangedEventCloudEvent(@RequestBody String uris) {
    UpstreamClusterChangedEvent upstreamClusterChangedEvent = new UpstreamClusterChangedEvent("", "*", "", Arrays.asList(uris.split(",")));

    // passing in the given attributes
    return CloudEventBuilder.<UpstreamClusterChangedEvent>builder()
            .withType("com.alibaba.rsocket.upstream.UpstreamClusterChangedEvent")
            .withId(UUID.randomUUID().toString())
            .withTime(ZonedDateTime.now())
            .withDataschema(URI.create("rsocket:event:com.alibaba.rsocket.upstream.UpstreamClusterChangedEvent"))
            .withDataContentType("application/json")
            .withSource(URI.create("broker://" + RSocketAppContext.ID))
            .withData(upstreamClusterChangedEvent)
            .build();
}
 
Example #18
Source File: DefaultAggregator.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private static CloudEventImpl<TraceEvent> buildDefaultCloudEvent(DMNModel model, String executionId, List<EvaluateEvent> events) {
    EvaluateEvent firstEvent = events.get(0);
    EvaluateEvent lastEvent = events.get(events.size() - 1);

    List<TraceInputValue> inputs = buildTraceInputValues(model, firstEvent);

    List<TraceOutputValue> outputs = buildTraceOutputValues(model, lastEvent);

    Pair<List<TraceExecutionStep>, List<Message>> executionStepsPair = buildTraceExecutionSteps(model, executionId, events);

    TraceHeader header = new TraceHeader(
            TraceEventType.DMN,
            executionId,
            firstEvent.getTimestamp(),
            lastEvent.getTimestamp(),
            computeDurationMillis(firstEvent, lastEvent),
            TraceResourceId.from(firstEvent),
            Stream.of(
                    model == null ? Stream.of(Message.from(InternalMessageType.DMN_MODEL_NOT_FOUND)) : Stream.<Message>empty(),
                    executionStepsPair.getRight().stream(),
                    lastEvent.getResult().getMessages().stream()
                            .filter(m -> m.getSourceId() == null || m.getSourceId().isBlank())
            ).flatMap(Function.identity()).collect(Collectors.toList())
    );

    // complete event
    TraceEvent event = new TraceEvent(header, inputs, outputs, executionStepsPair.getLeft());

    return CloudEventBuilder.<TraceEvent>builder()
            .withType(TraceEvent.class.getName())
            .withId(executionId)
            .withSource(buildSource(firstEvent))
            .withData(event)
            .build();
}
 
Example #19
Source File: OpsRestController.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@PostMapping("/broadcast/demo")
public Mono<Void> broadcastDemo(@RequestBody Map<String, Object> content) throws Exception {
    CloudEventImpl<Map<String, Object>> cloudEvent = CloudEventBuilder.<Map<String, Object>>builder()
            .withId(UUID.randomUUID().toString())
            .withSource(URI.create("broker://" + RSocketAppContext.ID))
            .withType("com.alibaba.demo.UnknownType")
            .withTime(ZonedDateTime.now())
            .withDataContentType("application/json")
            .withData(content)
            .withSubject("subject1")
            .build();
    return handlerRegistry.broadcast("*", cloudEvent);
}
 
Example #20
Source File: LiiklusCloudEvent.java    From liiklus with MIT License 5 votes vote down vote up
CloudEventImpl<ByteBuffer> toV1() {
    Map<String, String> rawExtensions = this.rawExtensions;
    return CloudEventBuilder.<ByteBuffer>builder()
            .withId(id)
            .withType(type)
            .withSource(getSource())
            .withDataContentType(mediaType)
            .withTime(getTime())
            .withExtension(new ExtensionFormat() {
                @Override
                public InMemoryFormat memory() {
                    return new InMemoryFormat() {
                        @Override
                        public String getKey() {
                            return "liiklusKV";
                        }

                        @Override
                        public Object getValue() {
                            return rawExtensions;
                        }

                        @Override
                        public Class<?> getValueType() {
                            return Map.class;
                        }
                    };
                }

                @Override
                public Map<String, String> transport() {
                    return rawExtensions;
                }
            })
            .withData(data)
            .build();
}
 
Example #21
Source File: JsonSchemaPreProcessorTest.java    From liiklus with MIT License 5 votes vote down vote up
@Test
void testCloudEvent() throws Exception {
    var processor = getProcessor();

    assertThatThrownBy(() -> {
        preProcess(processor,
                CloudEventBuilder.builder()
                        .withId(UUID.randomUUID().toString())
                        .withType("com.example.cloudevent")
                        .withSource(URI.create("/tests"))
                        .withDataContentType("application/json")
                        .withData(
                                JsonSchemaPreProcessor.JSON_MAPPER.writeValueAsBytes(
                                        Map.of("foo", 123)
                                )
                        )
                        .build()
        );
    }).hasMessageContaining("$.foo: integer found, string expected");

    preProcess(
            processor,
            CloudEventBuilder.builder()
                    .withId(UUID.randomUUID().toString())
                    .withType("com.example.cloudevent")
                    .withSource(URI.create("/tests"))
                    .withDataContentType("application/json")
                    .withData(
                            JsonSchemaPreProcessor.JSON_MAPPER.writeValueAsBytes(
                                    Map.of("foo", "bar")
                            )
                    )
                    .build()
    );
}
 
Example #22
Source File: RSocketEndpoint.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
public Mono<Void> sendAppStatus(Integer status) {
    final CloudEventImpl<AppStatusEvent> appStatusEventCloudEvent = CloudEventBuilder.<AppStatusEvent>builder()
            .withId(UUID.randomUUID().toString())
            .withTime(ZonedDateTime.now())
            .withSource(URI.create("app://" + RSocketAppContext.ID))
            .withType(AppStatusEvent.class.getCanonicalName())
            .withDataContentType("application/json")
            .withData(new AppStatusEvent(RSocketAppContext.ID, status))
            .build();
    return Flux.fromIterable(upstreamManager.findAllClusters()).flatMap(upstreamCluster -> upstreamCluster.getLoadBalancedRSocket().fireCloudEventToUpstreamAll(appStatusEventCloudEvent)).then();
}
 
Example #23
Source File: CloudEventMessageBuilder.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
public CloudEventMessageBuilder() {
    builder = CloudEventBuilder.builder();
}