sdk-java/cdi
Fabio José e815d7c75b Import the new v0.2 impl for CloudEvent
Signed-off-by: Fabio José <fabiojose@gmail.com>
2019-09-03 15:33:48 -03:00
..
src Import the new v0.2 impl for CloudEvent 2019-09-03 15:33:48 -03:00
README.md 📝 updating to 0.2.0 libraries for usage 2018-12-10 17:17:00 +01:00
pom.xml Update vesion and dep 2019-09-03 15:33:02 -03:00

README.md

CDI Integration

Firing CloudEvents using CDI

For Maven based projects, use the following to configure the CloudEvents CDI library:

<dependency>
    <groupId>io.cloudevents</groupId>
    <artifactId>cdi</artifactId>
    <version>0.2.0</version>
</dependency>

In Enterprise Java applications, implemented with Jakarta EE or the Eclipse MicroProfile, it's trivial to combine this CloudEvents API with CDI. Application developers can now fire a CloudEvent for further processing inside of the application:

import io.cloudevents.CloudEvent;
import io.cloudevents.CloudEventBuilder;
import io.cloudevents.cdi.EventTypeQualifier;

import javax.enterprise.event.Event;
import javax.inject.Inject;

import java.net.URI;
import java.util.UUID;

public class Router {

    @Inject
    private Event<CloudEvent<MyCustomEvent>> cloudEvent;

    public void routeMe() throws Exception {

        final CloudEvent<MyCustomEvent> event = new CloudEventBuilder<MyCustomEvent>()
                .type("Cloud.Storage.Item.Created")
                .source(new URI("/trigger"))
                .id(UUID.randomUUID().toString())
                .data(new MyCustomEvent(...))
                .build();

        cloudEvent.select(
                new EventTypeQualifier("Cloud.Storage.Item.Created"))
                .fire(event);
    }
}

The method above creates a CloudEvent object, and uses the injected CDI Event implementation, where a select() is performed to fire a qualified event, for all interested parties.

Receiving CloudEvents with CDI

If other parts of the application are interested in the Cloud.Storage.Item.Created event, it needs a matching @Observes annotation:

public void receiveCloudEvent(
  @Observes @EventType(name = "My.Cloud.Event.Type") CloudEvent cloudEvent) {
  // handle the event
}                                                                                       

The application now is able to work with the observed CloudEvent object.