diff --git a/sdk/eventgrid/azure-messaging-eventgrid/README.md b/sdk/eventgrid/azure-messaging-eventgrid/README.md index 1eb8f8bbe5414..ca18bd990bcd4 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/README.md +++ b/sdk/eventgrid/azure-messaging-eventgrid/README.md @@ -1,15 +1,15 @@ # Azure Event Grid client library for Java -This project provides client tools or utilities in Java that make it easy to interact with [Azure Event Grid][eventgrid]. - -Azure Event Grid is a fully-managed intelligent event routing service that provides reliable and scalable event delivery. - -The client library can be used to: - -- Publish events in the Event Grid, Cloud Event (1.0), or custom schema -- Decode and process events and event data at the event destination -- Generate shared access signatures that connect to an event topic - +Azure Event Grid allows you to easily build applications with event-based architectures. The Event Grid service fully +manages all routing of events from any source, to any destination, for any application. +Azure service events and custom events can be published directly to the service, where the events can then be filtered +and sent to various recipients, such as built-in handlers or custom webhooks. +To learn more about Azure Event Grid: [What is Event Grid?](https://docs.microsoft.com/azure/event-grid/overview) + +Use the client library for Azure Event Grid to: +- Publish events to the Event Grid service using the Event Grid Event, Cloud Event 1.0, or custom schemas +- Consume events that have been delivered to event handlers +- Generate SAS tokens to authenticate the client publishing events to Azure Event Grid topics [Sources][sources] | [API Reference Documentation][javadocs] | [Product Documentation][service_docs] | @@ -18,29 +18,14 @@ The client library can be used to: ## Getting started -### Install the Package - -To get the binaries of the official Microsoft Azure Event Grid Java SDK as distributed by Microsoft, ready for use -within your project, you can use [Maven][maven]. - -[//]: # ({x-version-update-start;com.azure:azure-messaging-eventgrid;current}) -```xml - - com.azure - azure-messaging-eventgrid - 2.0.0-beta.3 - -``` -[//]: # ({x-version-update-end}) - ### Prerequisites - [Java Development Kit (JDK) with version 8 or above][jdk] - An [Azure subscription][azure_subscription] -- An [Event Grid][eventgrid] topic or domain. To create the resource, you can use [Azure portal][portal] or -[Azure CLI][cli] +- An [Event Grid][eventgrid] topic or domain. To create the resource, you can use [Azure portal][portal] or + [Azure CLI][cli] -If you use the Azure CLI, replace `` and `` with your own unique names +If you use the Azure CLI, replace `` and `` with your own unique names and `` with a valid Azure service location. #### Creating a topic ([Azure CLI][cli]) @@ -56,10 +41,21 @@ az eventgrid topic create --location --resource-group --resource-group --name ``` +### Include the package +[//]: # ({x-version-update-start;com.azure:azure-messaging-eventgrid;current}) +```xml + + com.azure + azure-messaging-eventgrid + 2.0.0-beta.4 + +``` +[//]: # ({x-version-update-end}) + ### Authenticate the Client In order to send events, we need an endpoint to send to and some authentication for the endpoint, either as a -key credential or a shared access signature (which will in turn need an endpoint and key). +key credential or a shared access signature. The endpoint and key can both be obtained through [Azure Portal][portal] or [Azure CLI][cli]. #### Endpoint @@ -73,184 +69,257 @@ az eventgrid topic show --name --resource-group -```java -OffsetDateTime expiration = OffsetDateTime.now().plusMinutes(20); -String credentialString = EventGridSasCredential - .createSas(endpoint, expiration, new AzureKeyCredential(key)); -EventGridSasCredential signature = new EventGridSasCredential(credentialString); +```bash +az eventgrid topic key list --name --resource-group ``` #### Creating the Client -In order to start sending events, we need an `EventGridPublisherClient`. Here is code to -create the synchronous and the asynchronous versions. Note that a shared access signature can -be used instead of a key in any of these samples by calling the `sharedAccessSignatureCredential` -method instead of `keyCredential`. - +##### Using endpoint and access key to create the client +Once you have your access key and topic endpoint, you can create the publisher client as follows: - +Sync client that works for every Java developer: ```java EventGridPublisherClient egClient = new EventGridPublisherClientBuilder() - .endpoint(endpoint) - .credential(new AzureKeyCredential(key)) + .endpoint("") + .credential(new AzureKeyCredential("")) .buildClient(); ``` +or async client if your technology stack has reactive programming such as project reactor: +```java +EventGridPublisherAsyncClient egAsyncClient = new EventGridPublisherClientBuilder() + .endpoint("") + .credential(new AzureKeyCredential("")) + .buildAsyncClient(); +``` -or +##### Using endpoint and SAS token to create the client +If you have a SAS (**Shared Access Signature**) that can be used to send events to an Event Grid Topic or Domain for +limited time, you can use it to create the publisher client: - +Sync client: ```java -EventGridPublisherAsyncClient egAsyncClient = new EventGridPublisherClientBuilder() - .endpoint(endpoint) - .credential(new AzureKeyCredential(key)) +EventGridPublisherClient egClient = new EventGridPublisherClientBuilder() + .endpoint("") + .credential(new AzureSasCredential("")) + .buildClient(); +``` +Async client: +```java +EventGridPublisherAsyncClient egClient = new EventGridPublisherClientBuilder() + .endpoint("") + .credential(new AzureSasCredential("")) .buildAsyncClient(); ``` -## Key concepts +#### Create a SAS token for other people to send events for a limited period of time +If you'd like to give permission to other people to publish events to your Event Grid Topic or Domain for some time, you can create +a SAS (**Shared Access Signature**) for them so they can create an `EventGridPublisherClient` like the above to use `AzureSasCredential` +to create the publisher client. + +Here is sample code to create a shared access signature that expires after 20 minutes: +```java +OffsetDateTime expiration = OffsetDateTime.now().plusMinutes(20); + +String sasToken = EventGridSasGenerator + .generateSas("", new AzureKeyCredential(""), expiration); +``` + +## Key concepts +For information about general Event Grid concepts: [Concepts in Azure Event Grid](https://docs.microsoft.com/azure/event-grid/concepts). ### EventGridPublisherClient `EventGridPublisherClient` is used sending events to an Event Grid Topic or an Event Grid Domain. +`EventGridPublisherAsyncClient` is the async version of `EventGridPublisherClient`. ### Event Schemas -Event Grid supports multiple schemas for encoding events. When a Custom Topic or Domain is created, you specify the +Event Grid supports multiple schemas for encoding events. When an Event Grid Topic or Domain is created, you specify the schema that will be used when publishing events. While you may configure your topic to use a _custom schema_ it is -more common to use the already defined _Event Grid schema_ or _CloudEvents 1.0 schema_. -[CloudEvents](https://cloudevents.io/) is a Cloud Native Computing Foundation project which produces a specification -for describing event data in a common way. Regardless of what schema your topic or domain is configured to use, +more common to use the already defined [EventGridEvent schema](https://docs.microsoft.com/azure/event-grid/event-schema) or [CloudEvent schema](https://docs.microsoft.com/azure/event-grid/cloud-event-schema). +CloudEvent is a Cloud Native Computing Foundation project which produces a specification for describing event data in a common way. +Event Grid service is compatible with the [CloudEvent specification](https://cloudevents.io/) +Regardless of what schema your topic or domain is configured to use, `EventGridPublisherClient` will be used to publish events to it. However, you must use the correct method for publishing: -| Schema | Publishing Method | +| Event Schema | Publishing Method | | ------------ | --------------------- | -| Event Grid | `publishEvents` | -| Cloud Events | `publishCloudEvents` | -| Custom | `publishCustomEvents` | +| Event Grid Events | `sendEventGridEvents` | +| Cloud Events | `sendCloudEvents` | +| Custom Events | `sendCustomEvents` | + +Using the wrong method will result in a BadRequest error from the service and your events will not be published. +Use this Azure CLI command to query which schema an Event Grid Topic or Domain accepts: +```bash +az eventgrid topic show --name --resource-group --query inputSchema +``` -Using the wrong method will result in an error from the service and your events will not be published. +### Event Handlers and event deserialization. -### Consumption +EventGrid doesn't store any events in the Event Grid Topic or Domain itself. You need to [create subscriptions to the +EventGrid Topic or Domain](https://docs.microsoft.com/azure/event-grid/subscribe-through-portal). +The events sent to the topic or domain will be stored into the subscription's endpoint, also known as +["Event Handler"](https://docs.microsoft.com/azure/event-grid/event-handlers). -Events can be consumed from the event destination using respective schema class' `parse` method, passing the JSON string -received from the destination. +You may use the event handler's SDK to receive the events in Json String and then use the `EventGridEvent.fromString()` or `CloudEvent.fromString()` +deserialize the events. The data part of the events can be in binary, String, or JSON data. ## Examples -### Sending Events +### Sending Events To Event Grid Topics -Events can be sent in the `EventGridEvent`, `CloudEvent`, or a custom schema, as detailed in the Key Concepts above. +Events can be sent in the `EventGridEvent`, `CloudEvent`, or a custom schema, as detailed in [Event Schemas](#event-schemas). The topic or domain must be configured to accept the schema being sent. For simplicity, the synchronous client is used for samples, however the asynchronous client has the same method names. -#### `EventGridEvent` -The `EventGridEvent` model has 3 required properties to set: -- the subject, similar to a title or subject line of an email -- the event type, defining what kind of event happened -- the data version, identifying the current version of the data being sent - -These are set in the constructor, and a variety of other properties can be optionally set or overridden. -Learn more [here][EventGridEvent]. - +Note: figure out what schema (cloud event, event grid event, or custom event) the event grid topic accepts before you start sending. +#### Sending `EventGridEvent` to a topic that accepts EventGridEvent schema ```java +// Make sure that the event grid topic or domain you're sending to accepts EventGridEvent schema. List events = new ArrayList<>(); -events.add( - new EventGridEvent("exampleSubject", "Com.Example.ExampleEventType", "Example Data", - "1") -); - -egClient.sendEvents(events); +User user = new User("John", "James"); +events.add(new EventGridEvent("exampleSubject", "Com.Example.ExampleEventType", user, "v1")); +egClient.sendEventGridEvents(events); ``` -#### `CloudEvent` -The `CloudEvent` model has 2 required properties to set: -- the source, a URI identifying the source of the event -- the type, defining what kind of event happened. Note that this aligns with the "event type" of `EventGridEvent` - -These are set in the constructor, and a variety of other properties can be optionally set or overridden. -Learn more [here][CloudEvent]. - +#### Sending `CloudEvent` to a topic that accepts CloudEvent schema ```java +// Make sure that the event grid topic or domain you're sending to accepts CloudEvent schema. List events = new ArrayList<>(); -events.add( - new CloudEvent("com/example/source", "Com.Example.ExampleEventType") - .setData("Example Data") -); - +User user = new User("John", "James"); +events.add(new CloudEvent("https://source.example.com", "Com.Example.ExampleEventType", user)); egClient.sendCloudEvents(events); ``` -#### Custom Events +#### Sending Custom Events to a topic that accepts custom event schema To send custom events in any defined schema, use the `sendCustomEvents` method on the `PublisherClient`. -### Recieving and Consuming Events +### Sending Events To Event Grid Domain -Events can be sent to a variety of locations, including Azure services such as ServiceBus -or external endpoints such as a WebHook endpoint. However, currently all events will be -sent as encoded JSON data. Here is some basic code that details the handling -of an event. Again, the handling is different based on the event schema being received +An [Event Grid Domain](https://docs.microsoft.com/azure/event-grid/event-domains) can have thousands of topics +but has a single endpoint. You can use a domain to manage a set of related topics. Sending events to the topics of +an Event Grid Domain is the same as sending events to a regular Event Grid Topic except that you need to +specify the `topic` of an `EventGridEvent` if the domain accepts `EventGridEvent` schema. +```java +List events = new ArrayList<>(); +User user = new User("John", "James"); +events.add(new EventGridEvent("com/example", "Com.Example.ExampleEventType", user, "1") + .setTopic("yourtopic")); // Set it only when you send to an event grid domain. +egClient.sendEventGridEvents(events); +``` + +If the domain accepts `CloudEvent` schema, the CloudEvent's attribute that is configured to map the `topic` when the +domain is created must be set. The default mapping attribute is `source`. + +### Recieving and Consuming Events +The Event Grid service doesn't store events. So this Event Grid SDK doesn't have an event receiver. +Instead, events are stored in the [Event Handlers](#event-handlers-and-event-deserialization), including ServiceBus, EventHubs, Storage Queue, WebHook endpoint, or many other supported Azure Services. +However, currently all events will be sent and stored as encoded JSON data. Here is some basic code that details the deserialization +of events after they're received by the event handlers. Again, the handling is different based on the event schema being received from the topic/subscription. -#### `EventGridEvent` - +#### Deserialize `EventGridEvent` or `CloudEvent` from a Json String +The Json String can have a single event or an array of events. The returned result is a list of events. ```java -List events = EventGridEvent.parse(jsonData); - -for (EventGridEvent event : events) { - // system event data will be turned into it's rich object, - // while custom event data will be turned into a byte[]. - Object data = event.getData(); - - // this event type goes to any non-azure endpoint (such as a WebHook) when the subscription is created. - if (data instanceof SubscriptionValidationEventData) { - SubscriptionValidationEventData validationData = (SubscriptionValidationEventData) data; - System.out.println(validationData.getValidationCode()); - } else if (data instanceof byte[]) { - // we can turn the data into the correct type by calling this method. - // since we set the data as a string when sending, we pass the String class in to get it back. - String stringData = event.getData(String.class); - System.out.println(stringData); // "Example Data" - } -} +// Deserialize an EventGridEvent +String eventGridEventJsonData = "your EventGridEvent json String"; +List events = EventGridEvent.fromString(eventGridEventJsonData); + +// Deserialize a CloudEvent +String cloudEventJsonData = "your CloudEvent json String"; +List events = CloudEvent.fromString(cloudEventJsonData); ``` -#### `CloudEvent` - +#### Deserialize data from a `CloudEvent` or `EventGridEvent` +Once you deserialize the `EventGridEvent` or `CloudEvent` from a Json String, you can use `getData()` of +`CloudEvent` or `EventGridEvent` to get the payload of the event. It returns a `BinaryData` +object, which has methods to further deserialize the data into usable types: +- `BinaryData.toBytes()` gets the data as a byte[] +- `BinaryData.toString()` gets the data as a String +- `BinaryData.toObject()` gets the data as an object of a specific type. It uses Json deserializer by default. It has + an overload to accept your deserializer if you want to use your own. + +```java +BinaryData eventData = eventGridEvent.getData(); + +//Deserialize data to a model class +User dataInModelClass = eventData.toObject(TypeReference.createInstance(User.class)); + +//Deserialize data to a Map +Map dataMap = eventData.toObject(TypeReference.createInstance(Map.class)); + +//Deserialize data to a String +String dataString = eventData.toString(); + +//Deserialize data to byte array (byte[]) +byte[] dataInBytes = eventData.toBytes(); +``` + +#### Deserialize system event data from `CloudEvent` or `EventGridEvent` +An event that is sent to a [System Topic](https://docs.microsoft.com/azure/event-grid/system-topics) is called a +System Topic Event, or System Event. +A system topic in Event Grid represents events published by an [Event Source](https://docs.microsoft.com/azure/event-grid/overview#event-sources) like Azure Storage, Azure Event Hubs, App Configuration and so on. +An example is when a blob is created, a system event with event type "Microsoft.Storage.BlobCreated" is sent to the configured System Topic. +The system event class for this event type is `StorageBlobCreatedEventData` defined in package `com.azure.messaging.eventgrid.systemevents`. +EventGrid has system events for: +- [Azure App Configuration](https://docs.microsoft.com/azure/event-grid/event-schema-app-configuration) +- [Azure App Service](https://docs.microsoft.com/azure/event-grid/event-schema-app-service) +- [Azure Blob Storage](https://docs.microsoft.com/azure/event-grid/event-schema-blob-storage) +- ... +- Refer to [Azure services that support system topics](https://docs.microsoft.com/azure/event-grid/system-topics#azure-services-that-support-system-topics) for many other services. +- Refer to package `com.azure.messaging.eventgrid.systemevents` for the related system event classes + +You can't send a System Event to a System Topic by using this SDK. + +Receiving and consuming system events is the same as other events. Additionally, a set of model classes +for the various system event data are defined in package `com.azure.messaging.eventgrid.systemevents`. You can do the +following after you deserialize an event by using `EventGridEvent.fromString()` or `CloudEvent.fromString()`: +- look up the system event data model class that the System Event data can be deserialized to; +```java + Class eventDataClazz = SystemEventNames.getSystemEventMappings().get(event.getEventType()); +``` +- deserialize a system event's data to a model class instance like deserializing any other event data; +```java + // Deserialize the event data to an instance of a specific System Event data class type + BinaryData data = event.getData(); + if (data != null) { + StorageBlobCreatedEventData blobCreatedData = data.toObject(TypeReference.createInstance(StorageBlobCreatedEventData.class)); + System.out.println(blobCreatedData.getUrl()); + } +``` +- deal with multiple event types. ```java -List events = CloudEvent.parse(jsonData); - -for (CloudEvent event : events) { - // system event data will be turned into it's rich object, - // while custom event data will be turned into a byte[]. - Object data = event.getData(); - - // this event type goes to any non-azure endpoint (such as a WebHook) when the subscription is created. - if (data instanceof SubscriptionValidationEventData) { - SubscriptionValidationEventData validationData = (SubscriptionValidationEventData) data; - System.out.println(validationData.getValidationCode()); - } else if (data instanceof byte[]) { - // we can turn the data into the correct type by calling this method. - // since we set the data as a string when sending, we pass the String class in to get it back. - String stringData = event.getData(String.class); - System.out.println(stringData); // "Example Data" + List eventGridEvents = EventGridEvent.fromString(eventGridJsonString); + for (EventGridEvent eventGridEvent : eventGridEvents) { + BinaryData data = eventGridEvent.getData(); + switch (eventGridEvent.getEventType()) { + case SystemEventNames.APP_CONFIGURATION_KEY_VALUE_DELETED: + AppConfigurationKeyValueDeletedEventData keyValueDeletedEventData = + data.toObject(TypeReference.createInstance(AppConfigurationKeyValueDeletedEventData.class)); + System.out.println("Processing the AppConfigurationKeyValueDeletedEventData..."); + System.out.printf("The key is: %s%n", keyValueDeletedEventData.getKey()); + break; + case SystemEventNames.APP_CONFIGURATION_KEY_VALUE_MODIFIED: + AppConfigurationKeyValueModifiedEventData keyValueModifiedEventData = + data.toObject(TypeReference.createInstance(AppConfigurationKeyValueModifiedEventData.class)); + System.out.println("Processing the AppConfigurationKeyValueModifiedEventData..."); + System.out.printf("The key is: %s%n", keyValueModifiedEventData.getKey()); + break; + default: + System.out.printf("%s isn't an AppConfiguration event data%n", eventGridEvent.getEventType()); + break; + } } -} ``` -Some additional sample code can be found [here][samples]. -Be sure to check back for more samples in the future. +### More samples +Some additional sample code can be found [here][samples]. ## Troubleshooting @@ -300,7 +369,7 @@ This project has adopted the [Microsoft Open Source Code of Conduct](https://ope [azure_subscription]: https://azure.microsoft.com/free [maven]: https://maven.apache.org/ [HttpResponseException]: https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core/src/main/java/com/azure/core/exception/HttpResponseException.java -[samples]: https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid +[samples]: https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid [eventgrid]: https://azure.com/eventgrid [portal]: https://ms.portal.azure.com/ [cli]: https://docs.microsoft.com/cli/azure diff --git a/sdk/eventgrid/azure-messaging-eventgrid/pom.xml b/sdk/eventgrid/azure-messaging-eventgrid/pom.xml index 1634396e7773d..ec9f8cd68106e 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/pom.xml +++ b/sdk/eventgrid/azure-messaging-eventgrid/pom.xml @@ -71,17 +71,18 @@ azure-core-http-netty 1.7.1 + + com.azure azure-core-serializer-json-jackson 1.1.1 + test - - - commons-io - commons-io - 2.6 + com.azure + azure-storage-queue + 12.8.0 test @@ -121,4 +122,28 @@ test + + + + java-lts + + [11,) + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M3 + + + --add-opens com.azure.messaging.eventgrid/com.azure.messaging.eventgrid=ALL-UNNAMED + --add-opens com.azure.messaging.eventgrid/com.azure.messaging.eventgrid.implementation=ALL-UNNAMED + + + + + + + diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/CloudEvent.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/CloudEvent.java index dc5c01ec074df..ef5b551ff1ab6 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/CloudEvent.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/CloudEvent.java @@ -4,21 +4,12 @@ package com.azure.messaging.eventgrid; import com.azure.core.annotation.Fluent; -import com.azure.core.serializer.json.jackson.JacksonJsonSerializerBuilder; +import com.azure.core.util.BinaryData; import com.azure.core.util.CoreUtils; -import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.core.util.serializer.TypeReference; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; +import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -27,9 +18,18 @@ import java.util.UUID; /** - * The CloudEvent model. This represents a cloud event as specified by the CNCF, for sending event based data. - * @see EventGridPublisherAsyncClient - * @see EventGridPublisherClient + * The CloudEvent model. This represents a cloud event as specified by the + * Cloud Native Computing Foundation + * + * When you send a CloudEvent to an Event Grid Topic, the topic must be configured to receive the CloudEvent schema. + * + * For new customers, CloudEvent is generally preferred over {@link EventGridEvent} because the + * + * CloudEvent schema is supported across + * organizations while the EventGridEvent schema is not. + * + * @see EventGridPublisherAsyncClient to send cloud events asynchronously. + * @see EventGridPublisherClient to send cloud events. **/ @Fluent public final class CloudEvent { @@ -40,23 +40,38 @@ public final class CloudEvent { private static final ClientLogger logger = new ClientLogger(CloudEvent.class); - private boolean parsed = false; - - private static final JsonSerializer deserializer = new JacksonJsonSerializerBuilder() - .serializer(new JacksonAdapter().serializer() // this is a workaround to get the FlatteningDeserializer - .registerModule(new JavaTimeModule())) // probably also change this to DateTimeDeserializer when/if it - .build(); // becomes public in core + /** + * Create an instance of CloudEvent. The source and type are required fields to publish. + * @param source a URI identifying the origin of the event. It can't be null or empty. + * @param type the type of event, e.g. "Contoso.Items.ItemReceived". It can't be null or empty. + * @param data the payload of this event. Set to null if your event doesn't have the data payload. + * It will be serialized as a String if it's a String, or application/json if it's not a String. + * @throws NullPointerException if source or type is {@code null}. + */ + public CloudEvent(String source, String type, Object data) { + this(source, type); + this.setData(data); + } /** - * Create an instance of a CloudEvent. The source and type are required fields to publish. + * Create an instance of CloudEvent. The source and type are required fields to publish. * @param source a URI identifying the origin of the event. * @param type the type of event, e.g. "Contoso.Items.ItemReceived". + * @param data the payload in bytes of this event. It will be serialized to Base64 format. + * @param dataContentType the type of the data. + * @throws NullPointerException if source or type is {@code null}. */ - public CloudEvent(String source, String type) { + public CloudEvent(String source, String type, byte[] data, String dataContentType) { + this(source, type); + this.setDataBase64(data, dataContentType); + } + + private CloudEvent(String source, String type) { if (CoreUtils.isNullOrEmpty(source)) { - throw logger.logExceptionAsError(new IllegalArgumentException("Source cannot be null or empty")); - } else if (CoreUtils.isNullOrEmpty(type)) { - throw logger.logExceptionAsError(new IllegalArgumentException("type cannot be null or empty")); + throw logger.logExceptionAsError(new IllegalArgumentException("'source' cannot be null or empty.")); + } + if (CoreUtils.isNullOrEmpty(type)) { + throw logger.logExceptionAsError(new IllegalArgumentException("'type' cannot be null or empty.")); } this.cloudEvent = new com.azure.messaging.eventgrid.implementation.models.CloudEvent() @@ -65,30 +80,16 @@ public CloudEvent(String source, String type) { .setType(type) .setSpecversion(SPEC_VERSION); } - /** - * Parse the Cloud Event from a JSON string. This can be used to interpret the event at the event destination - * from raw JSON into rich event(s). - * @param json the JSON payload containing one or more events. + * Deserialize the {@link CloudEvent} from a JSON string. + * @param cloudEventJsonString the JSON payload containing one or more events. * - * @return all of the events in the payload parsed as CloudEvents. + * @return all of the events in the payload deserialized as {@link CloudEvent CloudEvents}. + * @throws IllegalArgumentException if cloudEventJsonString isn't a JSON string for a cloud event or an array of it. + * @throws NullPointerException if cloudEventJsonString is {@code null}. */ - public static List parse(String json) { - return Flux.fromArray(deserializer - .deserialize(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), - TypeReference.createInstance(com.azure.messaging.eventgrid.implementation.models.CloudEvent[].class)) - ) - .map(event1 -> { - if (event1.getData() != null) { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - deserializer.serialize(stream, event1.getData()); - return new CloudEvent(event1).setData(stream.toByteArray()); // use BinaryData instead? - } else { // both null, don't set data and keep null - return new CloudEvent(event1); - } - }) - .collectList() - .block(); + public static List fromString(String cloudEventJsonString) { + return EventGridDeserializer.deserializeCloudEvents(cloudEventJsonString); } /** @@ -122,131 +123,51 @@ public String getSource() { } /** - * Get the data associated with this event. For use in a parsed event only. - * @return If the event was parsed from a Json, this method will return the rich - * system event data if it is a system event, and a {@code byte[]} otherwise, such as in the case of binary event - * data, including data set through {@link CloudEvent#setData(byte[], String)}. - * @throws IllegalStateException If the event was not created through {@link EventGridEvent#parse(String)}. - */ - public Object getData() { - if (!parsed) { - // data was set instead of parsed, throw error - throw logger.logExceptionAsError(new IllegalStateException( - "This method should only be called on events created through the parse method")); - } - if (cloudEvent.getDataBase64() != null) { // this means normal data is null - return cloudEvent.getDataBase64(); - } - String eventType = SystemEventMappings.canonicalizeEventType(cloudEvent.getType()); - if (SystemEventMappings.getSystemEventMappings().containsKey(eventType)) { - // system event - return deserializer.deserialize(new ByteArrayInputStream((byte[]) this.cloudEvent.getData()), - TypeReference.createInstance(SystemEventMappings.getSystemEventMappings().get(eventType))); - } - return cloudEvent.getData(); - } - - /** - * Get the deserialized data property from the parsed event. Note that this is only intended to work on - * events with {@code application/json} data and has unspecified results on other media types, such as binary data. - * @param clazz the class of the type to deserialize the data into, using a default deserializer. - * @param the type to deserialize the data into. - * - * @return the data deserialized into the given type using a default deserializer. - * @throws IllegalStateException If the event was not created through {@link CloudEvent#parse(String)}. - */ - public T getData(Class clazz) { - return getDataAsync(clazz, deserializer).block(); - } - - /** - * Get the deserialized data property from the parsed event. Note that this is only intended to work on - * events with {@code application/json} data and has unspecified results on other media types, such as binary data. - * @param clazz the class of the type to deserialize the data into, using a default deserializer. - * @param the type to deserialize the data into. - * - * @return the data deserialized into the given type using a default deserializer, wrapped asynchronously in a - * {@link Mono}. - * @throws IllegalStateException If the event was not created through {@link CloudEvent#parse(String)}. - */ - public Mono getDataAsync(Class clazz) { - return getDataAsync(clazz, deserializer); - } - - /** - * Deserialize and get the data property from the parsed event. Note that this is only intended to work on - * events with {@code application/json} data and has unspecified results on other media types. - * @param clazz the class of the type to deserialize the data into. - * @param dataDeserializer the deserializer to use. - * @param the type to deserialize the data into. - * - * @return the data deserialized into the given type using the given deserializer. - * @throws IllegalStateException If the event was not created through {@link CloudEvent#parse(String)}. + * Get the data associated with this event as a {@link BinaryData}, which has API to deserialize the data into + * a String, an Object, or a byte[]. + * @return A {@link BinaryData} that wraps the this event's data payload. */ - public T getData(Class clazz, JsonSerializer dataDeserializer) { - return getDataAsync(clazz, dataDeserializer).block(); - } - - /** - * Deserialize and get the data property from the parsed event. Note that this is only intended to work on - * events with {@code application/json} data and has unspecified results on other media types. - * @param clazz the class of the type to deserialize the data into. - * @param dataDeserializer the deserializer to use. - * @param the type to deserialize the data into. - * - * @return the data deserialized into the given type using the given deserializer, wrapped asynchronously in a - * {@link Mono}. - * @throws IllegalStateException If the event was not created through {@link CloudEvent#parse(String)}. - */ - public Mono getDataAsync(Class clazz, JsonSerializer dataDeserializer) { - if (!parsed) { - // data was set instead of parsed, throw exception because we don't know how the data relates to clazz - return FluxUtil.monoError(logger, new IllegalStateException( - "This method should only be called on events created through the parse method")); + public BinaryData getData() { + if (cloudEvent.getDataBase64() != null) { + return BinaryData.fromBytes(cloudEvent.getDataBase64()); } - - return dataDeserializer.deserializeAsync(new ByteArrayInputStream((byte[]) this.cloudEvent.getData()), - TypeReference.createInstance(clazz)); + return EventGridDeserializer.getData(cloudEvent.getData()); } /** * Set the data associated with this event. - * @param data the data to set. Should be serializable with the serializer set on the publisher client. + * @param data the data to set. * * @return the cloud event itself. */ - public CloudEvent setData(Object data) { + CloudEvent setData(Object data) { this.cloudEvent.setData(data); return this; } /** - * Set the data associated with this event, along with a content type URI - * @param data the data to set. Should be serializable by the serializer set on the publisher client. - * @param dataContentType a URI identifying the MIME type of the data. - * For example, if the data was an XML string, the data content type could be - * {@code "application/xml"}. + * Set the Base64 data associated with this event. + * @param data the data to set. + * @param dataContentType the data content type of the CloudEvent. + * * @return the cloud event itself. */ - public CloudEvent setData(Object data, String dataContentType) { - this.cloudEvent.setData(data); - this.cloudEvent.setDatacontenttype(dataContentType); + private CloudEvent setDataBase64(byte[] data, String dataContentType) { + if (data != null) { + byte[] encoded = Base64.getEncoder().encode(data); + this.cloudEvent.setDataBase64(encoded); + this.cloudEvent.setDatacontenttype(dataContentType); + } return this; } /** - * Set byte data associated with this event, as well as the content type of the byte data. The data content - * type should be a string identifying the media type of the data. - * @param data the data to set. - * @param dataContentType the string identifying the media type of the byte data, as a MIME type. A null value will - * be interpreted as the {@code application/json} type. - * + * Set the data content type with this event. + * @param dataContentType the data content type to set. * @return the cloud event itself. */ - public CloudEvent setData(byte[] data, String dataContentType) { - this.cloudEvent - .setDataBase64(data) - .setDatacontenttype(dataContentType); + public CloudEvent setDataContentType(String dataContentType) { + this.cloudEvent.setDatacontenttype(dataContentType); return this; } @@ -324,14 +245,6 @@ public CloudEvent setSubject(String subject) { return this; } - /** - * Get the spec version that this cloud event adheres to. Note that only CloudEvents spec version 1.0 is supported. - * @return the cloud event spec version. - */ - public String getSpecVersion() { - return this.cloudEvent.getSpecversion(); - } - /** * Get a map of the additional user-defined attributes associated with this event. * @return the extension attributes as an unmodifiable map. @@ -344,7 +257,7 @@ public Map getExtensionAttributes() { } /** - * Add/Overwrite a single extension attribute to the cloud event envelope. The property name will be transformed + * Add/Overwrite a single extension attribute to the cloud event. The property name will be transformed * to lowercase and must not share a name with any reserved cloud event properties. * @param name the name of the attribute. * @param value the value to associate with the name. @@ -359,9 +272,8 @@ public CloudEvent addExtensionAttribute(String name, Object value) { return this; } - private CloudEvent(com.azure.messaging.eventgrid.implementation.models.CloudEvent impl) { + CloudEvent(com.azure.messaging.eventgrid.implementation.models.CloudEvent impl) { this.cloudEvent = impl; - this.parsed = true; } com.azure.messaging.eventgrid.implementation.models.CloudEvent toImpl() { diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridDeserializer.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridDeserializer.java new file mode 100644 index 0000000000000..c258ebe781c95 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridDeserializer.java @@ -0,0 +1,101 @@ +package com.azure.messaging.eventgrid; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.serializer.JsonSerializer; +import com.azure.core.util.serializer.JsonSerializerProviders; +import com.azure.core.util.serializer.TypeReference; + +import java.io.ByteArrayInputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * This is a convenience class that deserializes a json string into events. + * {@link #deserializeCloudEvents(String)} deserializes a JSON string into a list of {@link CloudEvent} instances. + * {@link #deserializeEventGridEvents(String)} deserializes a JSON string into a list of {@link EventGridEvent} + * instances. + * + */ +final class EventGridDeserializer { + private static final ClientLogger LOGGER = new ClientLogger(EventGridDeserializer.class); + + private EventGridDeserializer() { + // Hide the constructor + } + + static final JsonSerializer DESERIALIZER = JsonSerializerProviders.createInstance(); + + /** + * Deserialize the {@link EventGridEvent} from a JSON string. + * @param eventGridEventsJson the JSON payload containing one or more events. + * + * @return all of the events in the payload deserialized as {@link EventGridEvent}s. + * @throws IllegalArgumentException if the input parameter isn't a JSON string for a eventgrid event + * or an array of it. + */ + static List deserializeEventGridEvents(String eventGridEventsJson) { + try { + return Arrays.stream(DESERIALIZER + .deserialize(new ByteArrayInputStream(eventGridEventsJson.getBytes(StandardCharsets.UTF_8)), + TypeReference.createInstance(com.azure.messaging.eventgrid.implementation.models.EventGridEvent[].class))) + .map(internalEvent -> { + if (internalEvent.getSubject() == null || internalEvent.getEventType() == null + || internalEvent.getData() == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + "'subject', 'type', and 'data' are mandatory attributes for an EventGridEvent. " + + "Check if the input param is a JSON string for an EventGridEvent or an array of it.")); + } + return new EventGridEvent(internalEvent); + }) + .collect(Collectors.toList()); + } catch (UncheckedIOException uncheckedIOException) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException("The input parameter isn't a JSON string.", + uncheckedIOException.getCause())); + } + } + + /** + * Deserialize the {@link CloudEvent} from a JSON string. + * @param cloudEventsJson the JSON payload containing one or more events. + * + * @return all of the events in the payload deserialized as {@link CloudEvent}s. + * @throws IllegalArgumentException if the input parameter isn't a JSON string for a cloud event or an array of it. + */ + static List deserializeCloudEvents(String cloudEventsJson) { + try { + return Arrays.stream(DESERIALIZER + .deserialize(new ByteArrayInputStream(cloudEventsJson.getBytes(StandardCharsets.UTF_8)), + TypeReference.createInstance(com.azure.messaging.eventgrid.implementation.models.CloudEvent[].class)) + ) + .map(internalEvent -> { + if (internalEvent.getSource() == null || internalEvent.getType() == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + "'source' and 'type' are mandatory attributes for a CloudEvent. " + + "Check if the input param is a JSON string for a CloudEvent or an array of it.")); + } + return new CloudEvent(internalEvent); + }) + .collect(Collectors.toList()); + } catch (UncheckedIOException uncheckedIOException) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException("The input parameter isn't a JSON string.", + uncheckedIOException.getCause())); + } + } + + static BinaryData getData(Object data) { + if (data == null) { + return null; + } + if (data instanceof byte[]) { + return BinaryData.fromBytes((byte[]) data); + } + if (data instanceof String) { + return BinaryData.fromString((String) data); + } + return BinaryData.fromObject(data); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridEvent.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridEvent.java index 0dcfd4335fa3d..744f4387c06ac 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridEvent.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridEvent.java @@ -4,26 +4,23 @@ package com.azure.messaging.eventgrid; import com.azure.core.annotation.Fluent; -import com.azure.core.serializer.json.jackson.JacksonJsonSerializerBuilder; +import com.azure.core.util.BinaryData; import com.azure.core.util.CoreUtils; -import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.core.util.serializer.TypeReference; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Mono; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import java.util.List; import java.util.UUID; /** * The EventGridEvent model. This represents events in the EventGrid schema to be used with the EventGrid service. + * + * When you send a EventGridEvent to an Event Grid Topic, the topic must be configured to receive the EventGridEvent schema. + * + * For new customers, {@link CloudEvent} is generally preferred over EventGridEvent because the + * CloudEvent schema is supported across + * organizations while the EventGridEvent schema is not. + * * @see EventGridPublisherAsyncClient * @see EventGridPublisherClient **/ @@ -34,27 +31,22 @@ public final class EventGridEvent { private static final ClientLogger logger = new ClientLogger(EventGridEvent.class); - private boolean parsed = false; - - private static final JsonSerializer deserializer = new JacksonJsonSerializerBuilder() - .serializer(new JacksonAdapter().serializer() // this is a workaround to get the FlatteningDeserializer - .registerModule(new JavaTimeModule())) // probably also change this to DateTimeDeserializer when/if it - .build(); // becomes public in core - /** * Create a new instance of the EventGridEvent, with the given required fields. * @param subject the subject of the event. * @param eventType the type of the event, e.g. "Contoso.Items.ItemReceived". * @param data the data associated with this event. * @param dataVersion the version of the data sent along with the event. + * + * @throws IllegalArgumentException if subject, eventType or data is {@code null} or empty. */ public EventGridEvent(String subject, String eventType, Object data, String dataVersion) { if (CoreUtils.isNullOrEmpty(subject)) { - throw logger.logExceptionAsError(new IllegalArgumentException("subject cannot be null or empty")); + throw logger.logExceptionAsError(new IllegalArgumentException("'subject' cannot be null or empty.")); } else if (CoreUtils.isNullOrEmpty(eventType)) { - throw logger.logExceptionAsError(new IllegalArgumentException("event type cannot be null or empty")); + throw logger.logExceptionAsError(new IllegalArgumentException("'eventType' cannot be null or empty.")); } else if (CoreUtils.isNullOrEmpty(dataVersion)) { - throw logger.logExceptionAsError(new IllegalArgumentException("data version cannot be null or empty")); + throw logger.logExceptionAsError(new IllegalArgumentException("'dataVersion' cannot be null or empty.")); } this.event = new com.azure.messaging.eventgrid.implementation.models.EventGridEvent() @@ -67,27 +59,16 @@ public EventGridEvent(String subject, String eventType, Object data, String data } /** - * Parse the EventGrid Event from a JSON string. This can be used to interpret the event at the event destination - * from raw JSON into rich event(s). - * @param json the JSON payload containing one or more events. + * Deserialize the {@link EventGridEvent} from a JSON string. + * @param eventGridJsonString the JSON payload containing one or more events. * - * @return all of the events in the payload parsed as CloudEvents. + * @return all of the events in the payload deserialized as {@link EventGridEvent EventGridEvents}. + * @throws IllegalArgumentException if eventGridJsonString isn't a JSON string for a eventgrid event + * or an array of it. + * @throws NullPointerException if eventGridJsonString is {@code null}. */ - public static List parse(String json) { - return Flux.fromArray(deserializer - .deserialize(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), - TypeReference.createInstance(com.azure.messaging.eventgrid.implementation.models.EventGridEvent[].class)) - ) - .map(event -> { - if (event.getData() == null) { - return new EventGridEvent(event); - } - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - deserializer.serialize(stream, event.getData()); - return new EventGridEvent(event.setData(stream.toByteArray())); // use BinaryData instead? - }) - .collectList() - .block(); + public static List fromString(String eventGridJsonString) { + return EventGridDeserializer.deserializeEventGridEvents(eventGridJsonString); } @@ -107,7 +88,7 @@ public String getId() { */ public EventGridEvent setId(String id) { if (CoreUtils.isNullOrEmpty(id)) { - throw logger.logExceptionAsError(new IllegalArgumentException("id cannot be null or empty")); + throw logger.logExceptionAsError(new IllegalArgumentException("'id' cannot be null or empty.")); } this.event.setId(id); return this; @@ -140,87 +121,13 @@ public String getSubject() { return this.event.getSubject(); } - - /** - * Get the data associated with this event. For use in a parsed event only. - * @return If the event was parsed from a Json, this method will return the rich - * system event data if it is a system event, and a {@code byte[]} otherwise, such as in the case of custom event - * data. - * @throws IllegalStateException If the event was not created through {@link EventGridEvent#parse(String)}. - */ - public Object getData() { - if (!parsed) { - // data was set instead of parsed, throw error - throw logger.logExceptionAsError(new IllegalStateException( - "This method should only be called on events created through the parse method")); - } - String eventType = SystemEventMappings.canonicalizeEventType(event.getEventType()); - if (SystemEventMappings.getSystemEventMappings().containsKey(eventType)) { - // system event - return deserializer.deserialize(new ByteArrayInputStream((byte[]) this.event.getData()), - TypeReference.createInstance(SystemEventMappings.getSystemEventMappings().get(eventType))); - } - return event.getData(); - } - - /** - * Get the deserialized data property from the parsed event. The behavior is undefined if this method is called - * on an event that was not created through the parse method. - * @param clazz the class of the type to deserialize the data into. - * @param the type to deserialize the data into. - * - * @return the data deserialized into the given type using a default deserializer. - * @throws IllegalStateException If the event was not created through {@link EventGridEvent#parse(String)}. - */ - public T getData(Class clazz) { - return getDataAsync(clazz, deserializer).block(); - } - - /** - * Get the deserialized data property from the parsed event. - * @param clazz the class of the type to deserialize the data into. - * @param the type to deserialize the data into. - * - * @return the data deserialized into the given type using a default deserializer, delivered asynchronously through - * a {@link Mono}. - * @throws IllegalStateException If the event was not created through {@link EventGridEvent#parse(String)}. - */ - public Mono getDataAsync(Class clazz) { - return getDataAsync(clazz, deserializer); - } - - /** - * Get the deserialized data property from the parsed event. - * @param clazz the class of the type to deserialize the data into. - * @param dataDeserializer the deserializer to use. - * @param the type to deserialize the data into. - * - * @return the data deserialized into the given type using the given deserializer. - * @throws IllegalStateException If the event was not created through {@link EventGridEvent#parse(String)}. - */ - public T getData(Class clazz, JsonSerializer dataDeserializer) { - return getDataAsync(clazz, dataDeserializer).block(); - } - /** - * Get the deserialized data property from the parsed event. - * @param clazz the class of the type to deserialize the data into. - * @param dataDeserializer the deserializer to use. - * @param the type to deserialize the data into. - * - * @return the data deserialized into the given type using the given deserializer, delivered asynchronously through - * a {@link Mono}. - * @throws IllegalStateException If the event was not created through {@link EventGridEvent#parse(String)}. + * Get the data associated with this event as a {@link BinaryData}, which has API to deserialize the data into + * a String, an Object, or a byte[]. + * @return A {@link BinaryData} that wraps the this event's data payload. */ - public Mono getDataAsync(Class clazz, JsonSerializer dataDeserializer) { - if (!parsed) { - // data was set instead of parsed, throw exception because we don't know how the data relates to clazz - return FluxUtil.monoError(logger, new IllegalStateException( - "This method should only be called on events created through the parse method")); - } - - return dataDeserializer.deserializeAsync(new ByteArrayInputStream((byte[]) this.event.getData()), - TypeReference.createInstance(clazz)); + public BinaryData getData() { + return EventGridDeserializer.getData(event.getData()); } /** @@ -259,17 +166,8 @@ public String getDataVersion() { return this.event.getDataVersion(); } - /** - * Get the metadata version of this event. Note that metadata version is a read-only property set by the service. - * @return the metadata version of this event. - */ - public String getMetadataVersion() { - return this.event.getMetadataVersion(); - } - - private EventGridEvent(com.azure.messaging.eventgrid.implementation.models.EventGridEvent impl) { + EventGridEvent(com.azure.messaging.eventgrid.implementation.models.EventGridEvent impl) { this.event = impl; - parsed = true; } com.azure.messaging.eventgrid.implementation.models.EventGridEvent toImpl() { diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherAsyncClient.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherAsyncClient.java index c1c212d340d6d..0e518b59aeea8 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherAsyncClient.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherAsyncClient.java @@ -10,7 +10,7 @@ import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.SerializerAdapter; +import com.azure.core.util.serializer.ObjectSerializer; import com.azure.core.util.tracing.TracerProxy; import com.azure.messaging.eventgrid.implementation.Constants; import com.azure.messaging.eventgrid.implementation.EventGridPublisherClientImpl; @@ -18,6 +18,9 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import java.io.ByteArrayOutputStream; +import java.util.Base64; + import static com.azure.core.util.FluxUtil.monoError; import static com.azure.core.util.FluxUtil.withContext; import static com.azure.core.util.tracing.Tracer.AZ_TRACING_NAMESPACE_KEY; @@ -40,12 +43,12 @@ public final class EventGridPublisherAsyncClient { private final ClientLogger logger = new ClientLogger(EventGridPublisherAsyncClient.class); + private final ObjectSerializer eventDataSerializer; - EventGridPublisherAsyncClient(HttpPipeline pipeline, String hostname, SerializerAdapter serializerAdapter, - EventGridServiceVersion serviceVersion) { + EventGridPublisherAsyncClient(HttpPipeline pipeline, String hostname, EventGridServiceVersion serviceVersion, + ObjectSerializer eventDataSerializer) { this.impl = new EventGridPublisherClientImplBuilder() .pipeline(pipeline) - .serializerAdapter(serializerAdapter) .buildClient(); // currently the service version is hardcoded into the Impl client, but once another service version gets @@ -53,6 +56,7 @@ public final class EventGridPublisherAsyncClient { this.serviceVersion = serviceVersion; this.hostname = hostname; + this.eventDataSerializer = eventDataSerializer; } /** @@ -67,20 +71,29 @@ public EventGridServiceVersion getServiceVersion() { * Publishes the given EventGrid events to the set topic or domain. * @param events the EventGrid events to publish. * - * @return the completion. + * @return A {@link Mono} that completes when the events are sent to the service. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono sendEvents(Iterable events) { + public Mono sendEventGridEvents(Iterable events) { + return withContext(context -> sendEventGridEvents(events, context)); + } + + Mono sendEventGridEvents(Iterable events, Context context) { if (events == null) { return monoError(logger, new NullPointerException("'events' cannot be null.")); } - return withContext(context -> sendEvents(events, context)); - } - - Mono sendEvents(Iterable events, Context context) { final Context finalContext = context != null ? context : Context.NONE; return Flux.fromIterable(events) - .map(EventGridEvent::toImpl) + .map(event -> { + com.azure.messaging.eventgrid.implementation.models.EventGridEvent internalEvent = event.toImpl(); + if (this.eventDataSerializer != null && internalEvent.getData() != null) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + eventDataSerializer.serialize(bos, event.getData()); + internalEvent.setData(Base64.getEncoder().encode(bos.toByteArray())); + } + return internalEvent; + }) .collectList() .flatMap(list -> this.impl.publishEventsAsync(this.hostname, list, finalContext.addData(AZ_TRACING_NAMESPACE_KEY, Constants.EVENT_GRID_TRACING_NAMESPACE_VALUE))); @@ -90,21 +103,30 @@ Mono sendEvents(Iterable events, Context context) { * Publishes the given cloud events to the set topic or domain. * @param events the cloud events to publish. * - * @return the completion. + * @return A {@link Mono} that completes when the events are sent to the service. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono sendCloudEvents(Iterable events) { - if (events == null) { - return monoError(logger, new NullPointerException("'events' cannot be null.")); - } return withContext(context -> sendCloudEvents(events, context)); } Mono sendCloudEvents(Iterable events, Context context) { + if (events == null) { + return monoError(logger, new NullPointerException("'events' cannot be null.")); + } final Context finalContext = context != null ? context : Context.NONE; this.addCloudEventTracePlaceHolder(events); return Flux.fromIterable(events) - .map(CloudEvent::toImpl) + .map(event -> { + com.azure.messaging.eventgrid.implementation.models.CloudEvent internalEvent = event.toImpl(); + if (this.eventDataSerializer != null && internalEvent.getData() != null) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + eventDataSerializer.serialize(bos, event.getData()); + internalEvent.setData(Base64.getEncoder().encode(bos.toByteArray())); + } + return internalEvent; + }) .collectList() .flatMap(list -> this.impl.publishCloudEventEventsAsync(this.hostname, list, finalContext.addData(AZ_TRACING_NAMESPACE_KEY, Constants.EVENT_GRID_TRACING_NAMESPACE_VALUE))); @@ -114,7 +136,8 @@ Mono sendCloudEvents(Iterable events, Context context) { * Publishes the given custom events to the set topic or domain. * @param events the custom events to publish. * - * @return the completion. + * @return A {@link Mono} that completes when the events are sent to the service. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono sendCustomEvents(Iterable events) { @@ -125,6 +148,9 @@ public Mono sendCustomEvents(Iterable events) { } Mono sendCustomEvents(Iterable events, Context context) { + if (events == null) { + return monoError(logger, new NullPointerException("'events' cannot be null.")); + } final Context finalContext = context != null ? context : Context.NONE; return Flux.fromIterable(events) .collectList() @@ -137,16 +163,20 @@ Mono sendCustomEvents(Iterable events, Context context) { * @param events the EventGrid events to publish. * * @return the response from the EventGrid service. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> sendEventsWithResponse(Iterable events) { + public Mono> sendEventGridEventsWithResponse(Iterable events) { if (events == null) { return monoError(logger, new NullPointerException("'events' cannot be null.")); } - return withContext(context -> sendEventsWithResponse(events, context)); + return withContext(context -> sendEventGridEventsWithResponse(events, context)); } - Mono> sendEventsWithResponse(Iterable events, Context context) { + Mono> sendEventGridEventsWithResponse(Iterable events, Context context) { + if (events == null) { + return monoError(logger, new NullPointerException("'events' cannot be null.")); + } final Context finalContext = context != null ? context : Context.NONE; return Flux.fromIterable(events) .map(EventGridEvent::toImpl) @@ -160,6 +190,7 @@ Mono> sendEventsWithResponse(Iterable events, Con * @param events the cloud events to publish. * * @return the response from the EventGrid service. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> sendCloudEventsWithResponse(Iterable events) { @@ -170,6 +201,9 @@ public Mono> sendCloudEventsWithResponse(Iterable eve } Mono> sendCloudEventsWithResponse(Iterable events, Context context) { + if (events == null) { + return monoError(logger, new NullPointerException("'events' cannot be null.")); + } final Context finalContext = context != null ? context : Context.NONE; this.addCloudEventTracePlaceHolder(events); return Flux.fromIterable(events) @@ -184,6 +218,7 @@ Mono> sendCloudEventsWithResponse(Iterable events, Co * @param events the custom events to publish. * * @return the response from the EventGrid service. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> sendCustomEventsWithResponse(Iterable events) { @@ -194,6 +229,9 @@ public Mono> sendCustomEventsWithResponse(Iterable events } Mono> sendCustomEventsWithResponse(Iterable events, Context context) { + if (events == null) { + return monoError(logger, new NullPointerException("'events' cannot be null.")); + } final Context finalContext = context != null ? context : Context.NONE; return Flux.fromIterable(events) .collectList() diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherClient.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherClient.java index dda8793ac7c5a..3f30cc0d90f56 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherClient.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherClient.java @@ -20,7 +20,6 @@ public final class EventGridPublisherClient { EventGridPublisherAsyncClient asyncClient; - EventGridPublisherClient(EventGridPublisherAsyncClient client) { this.asyncClient = client; } @@ -36,15 +35,17 @@ public EventGridServiceVersion getServiceVersion() { /** * Publishes the given EventGrid events to the given topic or domain. * @param events the EventGrid events to publish. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public void sendEvents(Iterable events) { - asyncClient.sendEvents(events, Context.NONE).block(); + public void sendEventGridEvents(Iterable events) { + asyncClient.sendEventGridEvents(events, Context.NONE).block(); } /** * Publishes the given cloud events to the given topic or domain. * @param events the cloud events to publish. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public void sendCloudEvents(Iterable events) { @@ -54,6 +55,7 @@ public void sendCloudEvents(Iterable events) { /** * Publishes the given custom events to the given topic or domain. * @param events the custom events to publish. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public void sendCustomEvents(Iterable events) { @@ -66,10 +68,11 @@ public void sendCustomEvents(Iterable events) { * @param context the context to use along the pipeline. * * @return the response given by the EventGrid service. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response sendEventsWithResponse(Iterable events, Context context) { - return asyncClient.sendEventsWithResponse(events, context).block(); + public Response sendEventGridEventsWithResponse(Iterable events, Context context) { + return asyncClient.sendEventGridEventsWithResponse(events, context).block(); } /** @@ -78,6 +81,7 @@ public Response sendEventsWithResponse(Iterable events, Co * @param context the context to use along the pipeline. * * @return the response given by the EventGrid service. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response sendCloudEventsWithResponse(Iterable events, Context context) { @@ -90,6 +94,7 @@ public Response sendCloudEventsWithResponse(Iterable events, C * @param context the context to use along the pipeline. * * @return the response given by the EventGrid service. + * @throws NullPointerException if events is {@code null}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response sendCustomEventsWithResponse(Iterable events, Context context) { diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherClientBuilder.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherClientBuilder.java index 90118359a7bee..97fa22f7e2348 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherClientBuilder.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridPublisherClientBuilder.java @@ -5,10 +5,14 @@ import com.azure.core.annotation.ServiceClientBuilder; import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.credential.AzureSasCredential; import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeader; +import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpPipeline; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.AddHeadersPolicy; import com.azure.core.http.policy.AzureKeyCredentialPolicy; import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.http.policy.HttpLoggingPolicy; @@ -17,11 +21,11 @@ import com.azure.core.http.policy.RequestIdPolicy; import com.azure.core.http.policy.RetryPolicy; import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.util.ClientOptions; import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JacksonAdapter; -import com.azure.core.util.serializer.SerializerAdapter; +import com.azure.core.util.serializer.ObjectSerializer; import com.azure.core.util.tracing.TracerProxy; import com.azure.messaging.eventgrid.implementation.CloudEventTracingPipelinePolicy; @@ -57,11 +61,15 @@ public final class EventGridPublisherClientBuilder { private final List policies = new ArrayList<>(); + private ClientOptions clientOptions; + + private ObjectSerializer eventDataSerializer; + private Configuration configuration; private AzureKeyCredential keyCredential; - private EventGridSasCredential sasToken; + private AzureSasCredential sasToken; private EventGridServiceVersion serviceVersion; @@ -75,8 +83,6 @@ public final class EventGridPublisherClientBuilder { private RetryPolicy retryPolicy; - private SerializerAdapter serializer; - /** * Construct a new instance with default building settings. The endpoint and one credential method must be set * in order for the client to be built. @@ -92,7 +98,7 @@ public EventGridPublisherClientBuilder() { /** * Build a publisher client with asynchronous publishing methods and the current settings. An endpoint must be set, * and either a pipeline with correct authentication must be set, or a credential must be set in the form of - * an {@link EventGridSasCredential} or a {@link AzureKeyCredential} at the respective methods. + * an {@link AzureSasCredential} or a {@link AzureKeyCredential} at the respective methods. * All other settings have defaults and are optional. * @return a publisher client with asynchronous publishing methods. */ @@ -104,16 +110,12 @@ public EventGridPublisherAsyncClient buildAsyncClient() { throw logger.logExceptionAsError(new IllegalArgumentException("Cannot parse endpoint")); } - SerializerAdapter buildSerializer = serializer == null ? - JacksonAdapter.createDefaultSerializerAdapter() : - serializer; - EventGridServiceVersion buildServiceVersion = serviceVersion == null ? EventGridServiceVersion.getLatest() : serviceVersion; if (httpPipeline != null) { - return new EventGridPublisherAsyncClient(httpPipeline, hostname, buildSerializer, buildServiceVersion); + return new EventGridPublisherAsyncClient(httpPipeline, hostname, buildServiceVersion, eventDataSerializer); } Configuration buildConfiguration = (configuration == null) @@ -123,7 +125,10 @@ public EventGridPublisherAsyncClient buildAsyncClient() { // Closest to API goes first, closest to wire goes last. final List httpPipelinePolicies = new ArrayList<>(); - httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, + String applicationId = + clientOptions == null ? httpLogOptions.getApplicationId() : clientOptions.getApplicationId(); + + httpPipelinePolicies.add(new UserAgentPolicy(applicationId, clientName, clientVersion, buildConfiguration)); httpPipelinePolicies.add(new RequestIdPolicy()); @@ -135,7 +140,7 @@ public EventGridPublisherAsyncClient buildAsyncClient() { // Using token before key if both are set if (sasToken != null) { httpPipelinePolicies.add((context, next) -> { - context.getHttpRequest().getHeaders().put(AEG_SAS_TOKEN, sasToken.getSas()); + context.getHttpRequest().getHeaders().put(AEG_SAS_TOKEN, sasToken.getSignature()); return next.process(); }); } else { @@ -144,6 +149,13 @@ public EventGridPublisherAsyncClient buildAsyncClient() { httpPipelinePolicies.addAll(policies); + if (clientOptions != null) { + List httpHeaderList = new ArrayList<>(); + clientOptions.getHeaders().forEach(header -> + httpHeaderList.add(new HttpHeader(header.getName(), header.getValue()))); + policies.add(new AddHeadersPolicy(new HttpHeaders(httpHeaderList))); + } + HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); if (TracerProxy.isTracingEnabled()) { @@ -157,7 +169,7 @@ public EventGridPublisherAsyncClient buildAsyncClient() { .build(); - return new EventGridPublisherAsyncClient(buildPipeline, hostname, buildSerializer, buildServiceVersion); + return new EventGridPublisherAsyncClient(buildPipeline, hostname, buildServiceVersion, eventDataSerializer); } /** @@ -193,6 +205,21 @@ public EventGridPublisherClientBuilder retryPolicy(RetryPolicy retryPolicy) { return this; } + /** + * Sets the {@link ClientOptions} which enables various options to be set on the client. For example setting an + * {@code applicationId} using {@link ClientOptions#setApplicationId(String)} to configure + * the {@link UserAgentPolicy} for telemetry/monitoring purposes. + * + *

More About Azure Core: Telemetry policy + * + * @param clientOptions the {@link ClientOptions} to be set on the client. + * @return The updated EventGridPublisherClientBuilder object. + */ + public EventGridPublisherClientBuilder clientOptions(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + return this; + } + /** * Set the configuration of HTTP and Azure values. A default is already set. * @param configuration the configuration to use. @@ -221,7 +248,7 @@ public EventGridPublisherClientBuilder credential(AzureKeyCredential credential) * * @return the builder itself. */ - public EventGridPublisherClientBuilder credential(EventGridSasCredential credential) { + public EventGridPublisherClientBuilder credential(AzureSasCredential credential) { this.sasToken = credential; return this; } @@ -262,6 +289,16 @@ public EventGridPublisherClientBuilder httpLogOptions(HttpLogOptions httpLogOpti return this; } + /** + * Set the serializer that will serialize the data part of the events when the events are sent to the service. + * @param eventDataSerializer The data serializer. + * @return the builder itself. + */ + public EventGridPublisherClientBuilder serializer(ObjectSerializer eventDataSerializer) { + this.eventDataSerializer = eventDataSerializer; + return this; + } + /** * Set the HTTP pipeline to use when sending calls to the service. * @param httpPipeline the pipeline to use. @@ -288,15 +325,4 @@ public EventGridPublisherClientBuilder serviceVersion(EventGridServiceVersion se return this; } - /** - * Set the serializer to use when serializing events to be sent. Default is - * {@link JacksonAdapter#createDefaultSerializerAdapter()}. - * @param serializer the serializer to set. - * - * @return the builder itself. - */ - public EventGridPublisherClientBuilder serializer(SerializerAdapter serializer) { - this.serializer = serializer; - return this; - } } diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridSasCredential.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridSasGenerator.java similarity index 54% rename from sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridSasCredential.java rename to sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridSasGenerator.java index b9b1d0a4be423..d310e2031375a 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridSasCredential.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/EventGridSasGenerator.java @@ -1,9 +1,7 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - package com.azure.messaging.eventgrid; import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.credential.AzureSasCredential; import com.azure.core.util.logging.ClientLogger; import javax.crypto.Mac; @@ -20,32 +18,54 @@ import java.util.Base64; /** - * A way to use a generated shared access signature as a credential to publish events to a topic through a client. + * This is a utility to create a SAS, or Shared Access Signature token, from the endpoint and key of an + * Event Grid Topic or Domain. + * + * If you would like to grant somebody to publish events to your Event Grid Topic/Domain resource for a limited time, + * you could use this utility class to create a SAS token and share the token to them. They can then use + * {@link EventGridPublisherClientBuilder#credential(AzureSasCredential)} to to create a client to publish events. + * */ -public final class EventGridSasCredential { - - private String sas; +public final class EventGridSasGenerator { + private EventGridSasGenerator() { + // Hide the constructor + } + private static final ClientLogger logger = new ClientLogger(EventGridPublisherClient.class); - private static final ClientLogger logger = new ClientLogger(EventGridSasCredential.class); + /** + * Generate a shared access signature to provide time-limited authentication for requests to the Event Grid + * service with the latest Event Grid service API defined in {@link EventGridServiceVersion#getLatest()}. + * @param endpoint the endpoint of the Event Grid topic or domain. + * @param expirationTime the time in which the signature should expire, no longer providing authentication. + * @param keyCredential the access key obtained from the Event Grid topic or domain. + * + * @return the shared access signature string which can be used to construct an instance of + * {@link AzureSasCredential}. + */ + public static String generateSas(String endpoint, AzureKeyCredential keyCredential, OffsetDateTime expirationTime) { + return generateSas(endpoint, keyCredential, expirationTime, EventGridServiceVersion.getLatest()); + } /** * Generate a shared access signature to provide time-limited authentication for requests to the Event Grid * service. - * @param endpoint the endpoint of the Event Grid topic or domain. + * @param endpoint the endpoint of the Event Grid topic or domain. * @param expirationTime the time in which the signature should expire, no longer providing authentication. * @param keyCredential the access key obtained from the Event Grid topic or domain. + * @param apiVersion the EventGrid service api version defined in {@link EventGridServiceVersion} * * @return the shared access signature string which can be used to construct an instance of - * {@link EventGridSasCredential}. + * {@link AzureSasCredential}. */ - public static String createSas(String endpoint, OffsetDateTime expirationTime, - AzureKeyCredential keyCredential) { + public static String generateSas(String endpoint, AzureKeyCredential keyCredential, OffsetDateTime expirationTime, + EventGridServiceVersion apiVersion) { try { String resKey = "r"; String expKey = "e"; String signKey = "s"; Charset charset = StandardCharsets.UTF_8; + endpoint = endpoint + "?api-version=" + apiVersion.getVersion(); String encodedResource = URLEncoder.encode(endpoint, charset.name()); String encodedExpiration = URLEncoder.encode(expirationTime.atZoneSameInstant(ZoneOffset.UTC).format( DateTimeFormatter.ofPattern("M/d/yyyy h:m:s a")), @@ -67,35 +87,4 @@ public static String createSas(String endpoint, OffsetDateTime expirationTime, throw logger.logExceptionAsError(new RuntimeException(e)); } } - - /** - * Create an instance of this object to authenticate calls to the EventGrid service. - * @param sas the shared access signature to use. - */ - public EventGridSasCredential(String sas) { - if (sas == null) { - throw logger.logExceptionAsError(new IllegalArgumentException("the access signature cannot be null")); - } - if (sas.isEmpty()) { - throw logger.logExceptionAsError(new IllegalArgumentException("the access signature cannot be empty")); - } - this.sas = sas; - } - - /** - * Get the token string to authenticate service calls - * @return the Shared Access Signature as a string - */ - public String getSas() { - return sas; - } - - - /** - * Change the shared access signature token to a new one. - * @param sas the shared access signature token to use. - */ - public void update(String sas) { - this.sas = sas; - } } diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/SystemEventMappings.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java similarity index 55% rename from sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/SystemEventMappings.java rename to sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java index a029ce08f67ce..df159e59cc902 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/SystemEventMappings.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/com/azure/messaging/eventgrid/SystemEventNames.java @@ -80,6 +80,7 @@ import com.azure.messaging.eventgrid.systemevents.ServiceBusDeadletterMessagesAvailableWithNoListenersEventData; import com.azure.messaging.eventgrid.systemevents.StorageBlobCreatedEventData; import com.azure.messaging.eventgrid.systemevents.StorageBlobDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageBlobRenamedEventData; import com.azure.messaging.eventgrid.systemevents.SubscriptionDeletedEventData; import com.azure.messaging.eventgrid.systemevents.SubscriptionValidationEventData; import com.azure.messaging.eventgrid.systemevents.WebAppServicePlanUpdatedEventData; @@ -98,7 +99,6 @@ import java.util.Collections; import java.util.HashMap; -import java.util.Locale; import java.util.Map; /** @@ -108,74 +108,74 @@ * model class that the event string corresponds to in the {@code data} field, which is used to automatically deserialize * system events by their known string. */ -public final class SystemEventMappings { +public final class SystemEventNames { // Keep this sorted by the name of the service publishing the events. // AppConfiguration events. /** * indicate an event of KeyValueDeleted in AppConfiguration. */ - public static final String APP_CONFIGURATION_KEY_VALUE_DELETED_EVENT = "Microsoft.AppConfiguration.KeyValueDeleted"; + public static final String APP_CONFIGURATION_KEY_VALUE_DELETED = "Microsoft.AppConfiguration.KeyValueDeleted"; /** * indicate an event of KeyValueModified in AppConfiguration. */ - public static final String APP_CONFIGURATION_KEY_VALUE_MODIFIED_EVENT = "Microsoft.AppConfiguration.KeyValueModified"; + public static final String APP_CONFIGURATION_KEY_VALUE_MODIFIED = "Microsoft.AppConfiguration.KeyValueModified"; // ContainerRegistry events. /** * indicate an event of pushing an image to container registry. */ - public static final String CONTAINER_REGISTRY_IMAGE_PUSHED_EVENT = "Microsoft.ContainerRegistry.ImagePushed"; + public static final String CONTAINER_REGISTRY_IMAGE_PUSHED = "Microsoft.ContainerRegistry.ImagePushed"; /** * indicate an event of deleting an image from container registry. */ - public static final String CONTAINER_REGISTRY_IMAGE_DELETED_EVENT = "Microsoft.ContainerRegistry.ImageDeleted"; + public static final String CONTAINER_REGISTRY_IMAGE_DELETED = "Microsoft.ContainerRegistry.ImageDeleted"; /** * indicate an event of chart deletion in container registry. */ - public static final String CONTAINER_REGISTRY_CHART_DELETED_EVENT = "Microsoft.ContainerRegistry.ChartDeleted"; + public static final String CONTAINER_REGISTRY_CHART_DELETED = "Microsoft.ContainerRegistry.ChartDeleted"; /** * indicate an event of chart pushed in container registry. */ - public static final String CONTAINER_REGISTRY_CHART_PUSHED_EVENT = "Microsoft.ContainerRegistry.ChartPushed"; + public static final String CONTAINER_REGISTRY_CHART_PUSHED = "Microsoft.ContainerRegistry.ChartPushed"; // Device events. /** * indicate an event of creating an IoT hub device. */ - public static final String IOT_HUB_DEVICE_CREATED_EVENT = "Microsoft.Devices.DeviceCreated"; + public static final String IOT_HUB_DEVICE_CREATED = "Microsoft.Devices.DeviceCreated"; /** * indicate an event of deleting an IoT hub device. */ - public static final String IOT_HUB_DEVICE_DELETED_EVENT = "Microsoft.Devices.DeviceDeleted"; + public static final String IOT_HUB_DEVICE_DELETED = "Microsoft.Devices.DeviceDeleted"; /** * indicate an event of connecting an IoT hub device. */ - public static final String IOT_HUB_DEVICE_CONNECTED_EVENT = "Microsoft.Devices.DeviceConnected"; + public static final String IOT_HUB_DEVICE_CONNECTED = "Microsoft.Devices.DeviceConnected"; /** * indicate an event of disconnecting an IoT hub device. */ - public static final String IOT_HUB_DEVICE_DISCONNECTED_EVENT = "Microsoft.Devices.DeviceDisconnected"; + public static final String IOT_HUB_DEVICE_DISCONNECTED = "Microsoft.Devices.DeviceDisconnected"; /** * indicate an event of telemetry from an IoT hub device. */ - public static final String IOT_HUB_DEVICE_TELEMETRY_EVENT = "Microsoft.Devices.DeviceTelemetry"; + public static final String IOT_HUB_DEVICE_TELEMETRY = "Microsoft.Devices.DeviceTelemetry"; // EventGrid events. /** * indicate an event of validating eventgrid subscription. */ - public static final String EVENT_GRID_SUBSCRIPTION_VALIDATION_EVENT = "Microsoft.EventGrid.SubscriptionValidationEvent"; + public static final String EVENT_GRID_SUBSCRIPTION_VALIDATION = "Microsoft.EventGrid.SubscriptionValidationEvent"; /** * indicate an event of deleting eventgrid subscription. */ - public static final String EVENT_GRID_SUBSCRIPTION_DELETED_EVENT = "Microsoft.EventGrid.SubscriptionDeletedEvent"; + public static final String EVENT_GRID_SUBSCRIPTION_DELETED = "Microsoft.EventGrid.SubscriptionDeletedEvent"; // Event Hub Events. /** * indicate an event of creation of capture file in eventhub. */ - public static final String EVENT_HUB_CAPTURE_FILE_CREATED_EVENT = "Microsoft.EventHub.CaptureFileCreated"; + public static final String EVENT_HUB_CAPTURE_FILE_CREATED = "Microsoft.EventHub.CaptureFileCreated"; // Maps Events. /** @@ -197,181 +197,186 @@ public final class SystemEventMappings { /** * Media Services Job Canceled Event. */ - public static final String MEDIA_JOB_CANCELED_EVENT = "Microsoft.Media.JobCanceled"; + public static final String MEDIA_JOB_CANCELED = "Microsoft.Media.JobCanceled"; /** * Media Services Job Canceling Event. */ - public static final String MEDIA_JOB_CANCELING_EVENT = "Microsoft.Media.JobCanceling"; + public static final String MEDIA_JOB_CANCELING = "Microsoft.Media.JobCanceling"; /** * Media Services Job Errored event. */ - public static final String MEDIA_JOB_ERRORED_EVENT = "Microsoft.Media.JobErrored"; + public static final String MEDIA_JOB_ERRORED = "Microsoft.Media.JobErrored"; /** * Media Services Job Finished event. */ - public static final String MEDIA_JOB_FINISHED_EVENT = "Microsoft.Media.JobFinished"; + public static final String MEDIA_JOB_FINISHED = "Microsoft.Media.JobFinished"; /** * Media Services Job Ouput Canceled event. */ - public static final String MEDIA_JOB_OUTPUT_CANCELED_EVENT = "Microsoft.Media.JobOutputCanceled"; + public static final String MEDIA_JOB_OUTPUT_CANCELED = "Microsoft.Media.JobOutputCanceled"; /** * Media Services Job Output Canceling event. */ - public static final String MEDIA_JOB_OUTPUT_CANCELING_EVENT = "Microsoft.Media.JobOutputCanceling"; + public static final String MEDIA_JOB_OUTPUT_CANCELING = "Microsoft.Media.JobOutputCanceling"; /** * Media Services Job Output Errored event. */ - public static final String MEDIA_JOB_OUTPUT_ERRORED_EVENT = "Microsoft.Media.JobOutputErrored"; + public static final String MEDIA_JOB_OUTPUT_ERRORED = "Microsoft.Media.JobOutputErrored"; /** * Media Services Job Output Finished event. */ - public static final String MEDIA_JOB_OUTPUT_FINISHED_EVENT = "Microsoft.Media.JobOutputFinished"; + public static final String MEDIA_JOB_OUTPUT_FINISHED = "Microsoft.Media.JobOutputFinished"; /** * Media Services Job Output Processing event. */ - public static final String MEDIA_JOB_OUTPUT_PROCESSING_EVENT = "Microsoft.Media.JobOutputProcessing"; + public static final String MEDIA_JOB_OUTPUT_PROCESSING = "Microsoft.Media.JobOutputProcessing"; /** * Media Services Job Output Progress event. */ - public static final String MEDIA_JOB_OUTPUT_PROGRESS_EVENT = "Microsoft.Media.JobOutputProgress"; + public static final String MEDIA_JOB_OUTPUT_PROGRESS = "Microsoft.Media.JobOutputProgress"; /** * Media Services Job Output Scheduled event. */ - public static final String MEDIA_JOB_OUTPUT_SCHEDULED_EVENT = "Microsoft.Media.JobOutputScheduled"; + public static final String MEDIA_JOB_OUTPUT_SCHEDULED = "Microsoft.Media.JobOutputScheduled"; /** * Media Services Job Output State Change event. */ - public static final String MEDIA_JOB_OUTPUT_STATE_CHANGE_EVENT = "Microsoft.Media.JobOutputStateChange"; + public static final String MEDIA_JOB_OUTPUT_STATE_CHANGE = "Microsoft.Media.JobOutputStateChange"; /** * Media Services Job Processing event. */ - public static final String MEDIA_JOB_PROCESSING_EVENT = "Microsoft.Media.JobProcessing"; + public static final String MEDIA_JOB_PROCESSING = "Microsoft.Media.JobProcessing"; /** * Media Services Job Scheduled event. */ - public static final String MEDIA_JOB_SCHEDULED_EVENT = "Microsoft.Media.JobScheduled"; + public static final String MEDIA_JOB_SCHEDULED = "Microsoft.Media.JobScheduled"; /** * Media Services Job State Change event. */ - public static final String MEDIA_JOB_STATE_CHANGE_EVENT = "Microsoft.Media.JobStateChange"; + public static final String MEDIA_JOB_STATE_CHANGE = "Microsoft.Media.JobStateChange"; /** * Media Services Live Event Connection Rejected event. */ - public static final String MEDIA_LIVE_EVENT_CONNECTION_REJECTED_EVENT = "Microsoft.Media.LiveEventConnectionRejected"; + public static final String MEDIA_LIVE_EVENT_CONNECTION_REJECTED = "Microsoft.Media.LiveEventConnectionRejected"; /** * Media Services Live Event Encoder Connected event. */ - public static final String MEDIA_LIVE_EVENT_ENCODER_CONNECTED_EVENT = "Microsoft.Media.LiveEventEncoderConnected"; + public static final String MEDIA_LIVE_EVENT_ENCODER_CONNECTED = "Microsoft.Media.LiveEventEncoderConnected"; /** * Media Services Live Event Encoder Disconnected event. */ - public static final String MEDIA_LIVE_EVENT_ENCODER_DISCONNECTED_EVENT = "Microsoft.Media.LiveEventEncoderDisconnected"; + public static final String MEDIA_LIVE_EVENT_ENCODER_DISCONNECTED = "Microsoft.Media.LiveEventEncoderDisconnected"; /** * Media Services Live Event Incoming Data Chunk Dropped event. */ - public static final String MEDIA_LIVE_EVENT_INCOMING_DATA_CHUNK_DROPPED_EVENT = "Microsoft.Media.LiveEventIncomingDataChunkDropped"; + public static final String MEDIA_LIVE_EVENT_INCOMING_DATA_CHUNK_DROPPED = "Microsoft.Media.LiveEventIncomingDataChunkDropped"; /** * Media Services Live Event Incoming Stream Received event. */ - public static final String MEDIA_LIVE_EVENT_INCOMING_STREAM_RECEIVED_EVENT = "Microsoft.Media.LiveEventIncomingStreamReceived"; + public static final String MEDIA_LIVE_EVENT_INCOMING_STREAM_RECEIVED = "Microsoft.Media.LiveEventIncomingStreamReceived"; /** * Media Services Live Event Incoming Streams OutofSync event. */ - public static final String MEDIA_LIVE_EVENT_INCOMING_STREAMS_OUTOFSYNC_EVENT = "Microsoft.Media.LiveEventIncomingStreamsOutOfSync"; + public static final String MEDIA_LIVE_EVENT_INCOMING_STREAMS_OUTOFSYNC = "Microsoft.Media.LiveEventIncomingStreamsOutOfSync"; /** * Media Services Live Event Incoming Video Streams OutOfSync event. */ - public static final String MEDIA_LIVE_EVENT_INCOMING_VIDEO_STREAMS_OUTOFSYNC_EVENT = "Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync"; + public static final String MEDIA_LIVE_EVENT_INCOMING_VIDEO_STREAMS_OUTOFSYNC = "Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync"; /** * Media Services Live Event Ingest Heartbeat event. */ - public static final String MEDIA_LIVE_EVENT_INGEST_HEARTBEAT_EVENT = "Microsoft.Media.LiveEventIngestHeartbeat"; + public static final String MEDIA_LIVE_EVENT_INGEST_HEARTBEAT = "Microsoft.Media.LiveEventIngestHeartbeat"; /** * Media Services Live Event Track Discontinuity Detected event. */ - public static final String MEDIA_LIVE_EVENT_TRACK_DISCONTINUITY_DETECTED_EVENT = "Microsoft.Media.LiveEventTrackDiscontinuityDetected"; + public static final String MEDIA_LIVE_EVENT_TRACK_DISCONTINUITY_DETECTED = "Microsoft.Media.LiveEventTrackDiscontinuityDetected"; // Resource Manager (Azure Subscription/Resource Group) events /** * indicate an event of successful write of a resource. */ - public static final String RESOURCE_WRITE_SUCCESS_EVENT = "Microsoft.Resources.ResourceWriteSuccess"; + public static final String RESOURCE_WRITE_SUCCESS = "Microsoft.Resources.ResourceWriteSuccess"; /** * indicate an event of write failure of a resource. */ - public static final String RESOURCE_WRITE_FAILURE_EVENT = "Microsoft.Resources.ResourceWriteFailure"; + public static final String RESOURCE_WRITE_FAILURE = "Microsoft.Resources.ResourceWriteFailure"; /** * indicate an event of write cancellation of a resource. */ - public static final String RESOURCE_WRITE_CANCEL_EVENT = "Microsoft.Resources.ResourceWriteCancel"; + public static final String RESOURCE_WRITE_CANCEL = "Microsoft.Resources.ResourceWriteCancel"; /** * indicate an event of successful deletion of a resource. */ - public static final String RESOURCE_DELETE_SUCCESS_EVENT = "Microsoft.Resources.ResourceDeleteSuccess"; + public static final String RESOURCE_DELETE_SUCCESS = "Microsoft.Resources.ResourceDeleteSuccess"; /** * indicate an event of failure in deleting a resource. */ - public static final String RESOURCE_DELETE_FAILURE_EVENT = "Microsoft.Resources.ResourceDeleteFailure"; + public static final String RESOURCE_DELETE_FAILURE = "Microsoft.Resources.ResourceDeleteFailure"; /** * indicate an event of cancellation of resource deletion. */ - public static final String RESOURCE_DELETE_CANCEL_EVENT = "Microsoft.Resources.ResourceDeleteCancel"; + public static final String RESOURCE_DELETE_CANCEL = "Microsoft.Resources.ResourceDeleteCancel"; /** * indicate an event of successful action on a resource. */ - public static final String RESOURCE_ACTION_SUCCESS_EVENT = "Microsoft.Resources.ResourceActionSuccess"; + public static final String RESOURCE_ACTION_SUCCESS = "Microsoft.Resources.ResourceActionSuccess"; /** * indicate an event of failure in performing an action on a resource. */ - public static final String RESOURCE_ACTION_FAILURE_EVENT = "Microsoft.Resources.ResourceActionFailure"; + public static final String RESOURCE_ACTION_FAILURE = "Microsoft.Resources.ResourceActionFailure"; /** * indicate an event of cancellation of resource action. */ - public static final String RESOURCE_ACTION_CANCEL_EVENT = "Microsoft.Resources.ResourceActionCancel"; + public static final String RESOURCE_ACTION_CANCEL = "Microsoft.Resources.ResourceActionCancel"; // ServiceBus events. /** * indicate an event of active messages with no listener for them. */ - public static final String SERVICE_BUS_ACTIVE_MESSAGES_AVAILABLE_WITH_NO_LISTENERS_EVENT = "Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners"; + public static final String SERVICE_BUS_ACTIVE_MESSAGES_AVAILABLE_WITH_NO_LISTENERS = "Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners"; /** * indicate an event of deadletter messages with no listener for them. */ - public static final String SERVICE_BUS_DEADLETTER_MESSAGES_AVAILABLE_WITH_NO_LISTENER_EVENT = "Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener"; + public static final String SERVICE_BUS_DEADLETTER_MESSAGES_AVAILABLE_WITH_NO_LISTENER = "Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener"; // Storage events. /** * indicates an event of blob creation. */ - public static final String STORAGE_BLOB_CREATED_EVENT = "Microsoft.Storage.BlobCreated"; + public static final String STORAGE_BLOB_CREATED = "Microsoft.Storage.BlobCreated"; /** * indicates an event of blob deletion. */ - public static final String STORAGE_BLOB_DELETED_EVENT = "Microsoft.Storage.BlobDeleted"; + public static final String STORAGE_BLOB_DELETED = "Microsoft.Storage.BlobDeleted"; + + /** + * indicates an event of blob renaming. + */ + public static final String STORAGE_BLOB_RENAMED = "Microsoft.Storage.BlobRenamed"; // Communication Services events. public static final String COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER = @@ -429,145 +434,129 @@ public final class SystemEventMappings { public static final String KEY_VAULT_SECRET_EXPIRED = "Microsoft.KeyVault.SecretExpired"; public static final String KEY_VAULT_VAULT_ACCESS_POLICY_CHANGED = "Microsoft.KeyVault.VaultAccessPolicyChanged"; - //TODO: When a new service adds an event, add a constant above and a mapping to the corresponding data class below. - private static final Map> systemEventMappings = new HashMap>() {{ // // AppConfiguration events. - put(canonicalizeEventType(APP_CONFIGURATION_KEY_VALUE_DELETED_EVENT), AppConfigurationKeyValueDeletedEventData.class); - put(canonicalizeEventType(APP_CONFIGURATION_KEY_VALUE_MODIFIED_EVENT), AppConfigurationKeyValueModifiedEventData.class); + put(APP_CONFIGURATION_KEY_VALUE_DELETED , AppConfigurationKeyValueDeletedEventData.class); + put(APP_CONFIGURATION_KEY_VALUE_MODIFIED , AppConfigurationKeyValueModifiedEventData.class); // // ContainerRegistry events. - put(canonicalizeEventType(CONTAINER_REGISTRY_IMAGE_PUSHED_EVENT), ContainerRegistryImagePushedEventData.class); - put(canonicalizeEventType(CONTAINER_REGISTRY_IMAGE_DELETED_EVENT), ContainerRegistryImageDeletedEventData.class); - put(canonicalizeEventType(CONTAINER_REGISTRY_CHART_DELETED_EVENT), ContainerRegistryChartDeletedEventData.class); - put(canonicalizeEventType(CONTAINER_REGISTRY_CHART_PUSHED_EVENT), ContainerRegistryChartPushedEventData.class); + put(CONTAINER_REGISTRY_IMAGE_PUSHED , ContainerRegistryImagePushedEventData.class); + put(CONTAINER_REGISTRY_IMAGE_DELETED , ContainerRegistryImageDeletedEventData.class); + put(CONTAINER_REGISTRY_CHART_DELETED , ContainerRegistryChartDeletedEventData.class); + put(CONTAINER_REGISTRY_CHART_PUSHED , ContainerRegistryChartPushedEventData.class); // // Device events. - put(canonicalizeEventType(IOT_HUB_DEVICE_CREATED_EVENT), IotHubDeviceCreatedEventData.class); - put(canonicalizeEventType(IOT_HUB_DEVICE_DELETED_EVENT), IotHubDeviceDeletedEventData.class); - put(canonicalizeEventType(IOT_HUB_DEVICE_CONNECTED_EVENT), IotHubDeviceConnectedEventData.class); - put(canonicalizeEventType(IOT_HUB_DEVICE_DISCONNECTED_EVENT), IotHubDeviceDisconnectedEventData.class); - put(canonicalizeEventType(IOT_HUB_DEVICE_TELEMETRY_EVENT), IotHubDeviceTelemetryEventData.class); + put(IOT_HUB_DEVICE_CREATED , IotHubDeviceCreatedEventData.class); + put(IOT_HUB_DEVICE_DELETED , IotHubDeviceDeletedEventData.class); + put(IOT_HUB_DEVICE_CONNECTED , IotHubDeviceConnectedEventData.class); + put(IOT_HUB_DEVICE_DISCONNECTED , IotHubDeviceDisconnectedEventData.class); + put(IOT_HUB_DEVICE_TELEMETRY , IotHubDeviceTelemetryEventData.class); // // EventGrid events. - put(canonicalizeEventType(EVENT_GRID_SUBSCRIPTION_VALIDATION_EVENT), SubscriptionValidationEventData.class); - put(canonicalizeEventType(EVENT_GRID_SUBSCRIPTION_DELETED_EVENT), SubscriptionDeletedEventData.class); + put(EVENT_GRID_SUBSCRIPTION_VALIDATION , SubscriptionValidationEventData.class); + put(EVENT_GRID_SUBSCRIPTION_DELETED , SubscriptionDeletedEventData.class); // // Event Hub Events. - put(canonicalizeEventType(EVENT_HUB_CAPTURE_FILE_CREATED_EVENT), EventHubCaptureFileCreatedEventData.class); + put(EVENT_HUB_CAPTURE_FILE_CREATED , EventHubCaptureFileCreatedEventData.class); // Maps events - put(canonicalizeEventType(MAPS_GEOFENCE_ENTERED), MapsGeofenceEnteredEventData.class); - put(canonicalizeEventType(MAPS_GEOFENCE_EXITED), MapsGeofenceExitedEventData.class); - put(canonicalizeEventType(MAPS_GEOFENCE_RESULT), MapsGeofenceResultEventData.class); + put(MAPS_GEOFENCE_ENTERED, MapsGeofenceEnteredEventData.class); + put(MAPS_GEOFENCE_EXITED, MapsGeofenceExitedEventData.class); + put(MAPS_GEOFENCE_RESULT, MapsGeofenceResultEventData.class); // // Media Services events. - put(canonicalizeEventType(MEDIA_JOB_CANCELED_EVENT), MediaJobCanceledEventData.class); - put(canonicalizeEventType(MEDIA_JOB_CANCELING_EVENT), MediaJobCancelingEventData.class); - put(canonicalizeEventType(MEDIA_JOB_ERRORED_EVENT), MediaJobErroredEventData.class); - put(canonicalizeEventType(MEDIA_JOB_FINISHED_EVENT), MediaJobFinishedEventData.class); - put(canonicalizeEventType(MEDIA_JOB_OUTPUT_CANCELED_EVENT), MediaJobOutputCanceledEventData.class); - put(canonicalizeEventType(MEDIA_JOB_OUTPUT_CANCELING_EVENT), MediaJobOutputCancelingEventData.class); - put(canonicalizeEventType(MEDIA_JOB_OUTPUT_ERRORED_EVENT), MediaJobOutputErroredEventData.class); - put(canonicalizeEventType(MEDIA_JOB_OUTPUT_FINISHED_EVENT), MediaJobOutputFinishedEventData.class); - put(canonicalizeEventType(MEDIA_JOB_OUTPUT_PROCESSING_EVENT), MediaJobOutputProcessingEventData.class); - put(canonicalizeEventType(MEDIA_JOB_OUTPUT_PROGRESS_EVENT), MediaJobOutputProgressEventData.class); - put(canonicalizeEventType(MEDIA_JOB_OUTPUT_SCHEDULED_EVENT), MediaJobOutputScheduledEventData.class); - put(canonicalizeEventType(MEDIA_JOB_OUTPUT_STATE_CHANGE_EVENT), MediaJobOutputStateChangeEventData.class); - put(canonicalizeEventType(MEDIA_JOB_PROCESSING_EVENT), MediaJobProcessingEventData.class); - put(canonicalizeEventType(MEDIA_JOB_SCHEDULED_EVENT), MediaJobScheduledEventData.class); - put(canonicalizeEventType(MEDIA_JOB_STATE_CHANGE_EVENT), MediaJobStateChangeEventData.class); - put(canonicalizeEventType(MEDIA_LIVE_EVENT_CONNECTION_REJECTED_EVENT), MediaLiveEventConnectionRejectedEventData.class); - put(canonicalizeEventType(MEDIA_LIVE_EVENT_ENCODER_CONNECTED_EVENT), MediaLiveEventEncoderConnectedEventData.class); - put(canonicalizeEventType(MEDIA_LIVE_EVENT_ENCODER_DISCONNECTED_EVENT), MediaLiveEventEncoderDisconnectedEventData.class); - put(canonicalizeEventType(MEDIA_LIVE_EVENT_INCOMING_DATA_CHUNK_DROPPED_EVENT), MediaLiveEventIncomingDataChunkDroppedEventData.class); - put(canonicalizeEventType(MEDIA_LIVE_EVENT_INCOMING_STREAMS_OUTOFSYNC_EVENT), MediaLiveEventIncomingStreamsOutOfSyncEventData.class); - put(canonicalizeEventType(MEDIA_LIVE_EVENT_INCOMING_STREAM_RECEIVED_EVENT), MediaLiveEventIncomingStreamReceivedEventData.class); - put(canonicalizeEventType(MEDIA_LIVE_EVENT_INCOMING_VIDEO_STREAMS_OUTOFSYNC_EVENT), MediaLiveEventIncomingVideoStreamsOutOfSyncEventData.class); - put(canonicalizeEventType(MEDIA_LIVE_EVENT_INGEST_HEARTBEAT_EVENT), MediaLiveEventIngestHeartbeatEventData.class); - put(canonicalizeEventType(MEDIA_LIVE_EVENT_TRACK_DISCONTINUITY_DETECTED_EVENT), MediaLiveEventTrackDiscontinuityDetectedEventData.class); + put(MEDIA_JOB_CANCELED , MediaJobCanceledEventData.class); + put(MEDIA_JOB_CANCELING , MediaJobCancelingEventData.class); + put(MEDIA_JOB_ERRORED , MediaJobErroredEventData.class); + put(MEDIA_JOB_FINISHED , MediaJobFinishedEventData.class); + put(MEDIA_JOB_OUTPUT_CANCELED , MediaJobOutputCanceledEventData.class); + put(MEDIA_JOB_OUTPUT_CANCELING , MediaJobOutputCancelingEventData.class); + put(MEDIA_JOB_OUTPUT_ERRORED , MediaJobOutputErroredEventData.class); + put(MEDIA_JOB_OUTPUT_FINISHED , MediaJobOutputFinishedEventData.class); + put(MEDIA_JOB_OUTPUT_PROCESSING , MediaJobOutputProcessingEventData.class); + put(MEDIA_JOB_OUTPUT_PROGRESS , MediaJobOutputProgressEventData.class); + put(MEDIA_JOB_OUTPUT_SCHEDULED , MediaJobOutputScheduledEventData.class); + put(MEDIA_JOB_OUTPUT_STATE_CHANGE , MediaJobOutputStateChangeEventData.class); + put(MEDIA_JOB_PROCESSING , MediaJobProcessingEventData.class); + put(MEDIA_JOB_SCHEDULED , MediaJobScheduledEventData.class); + put(MEDIA_JOB_STATE_CHANGE , MediaJobStateChangeEventData.class); + put(MEDIA_LIVE_EVENT_CONNECTION_REJECTED , MediaLiveEventConnectionRejectedEventData.class); + put(MEDIA_LIVE_EVENT_ENCODER_CONNECTED , MediaLiveEventEncoderConnectedEventData.class); + put(MEDIA_LIVE_EVENT_ENCODER_DISCONNECTED , MediaLiveEventEncoderDisconnectedEventData.class); + put(MEDIA_LIVE_EVENT_INCOMING_DATA_CHUNK_DROPPED , MediaLiveEventIncomingDataChunkDroppedEventData.class); + put(MEDIA_LIVE_EVENT_INCOMING_STREAMS_OUTOFSYNC , MediaLiveEventIncomingStreamsOutOfSyncEventData.class); + put(MEDIA_LIVE_EVENT_INCOMING_STREAM_RECEIVED , MediaLiveEventIncomingStreamReceivedEventData.class); + put(MEDIA_LIVE_EVENT_INCOMING_VIDEO_STREAMS_OUTOFSYNC , MediaLiveEventIncomingVideoStreamsOutOfSyncEventData.class); + put(MEDIA_LIVE_EVENT_INGEST_HEARTBEAT , MediaLiveEventIngestHeartbeatEventData.class); + put(MEDIA_LIVE_EVENT_TRACK_DISCONTINUITY_DETECTED , MediaLiveEventTrackDiscontinuityDetectedEventData.class); // // Resource Manager (Azure Subscription/Resource Group) events. - put(canonicalizeEventType(RESOURCE_WRITE_SUCCESS_EVENT), ResourceWriteSuccessData.class); - put(canonicalizeEventType(RESOURCE_WRITE_FAILURE_EVENT), ResourceWriteFailureData.class); - put(canonicalizeEventType(RESOURCE_WRITE_CANCEL_EVENT), ResourceWriteCancelData.class); - put(canonicalizeEventType(RESOURCE_DELETE_SUCCESS_EVENT), ResourceDeleteSuccessData.class); - put(canonicalizeEventType(RESOURCE_DELETE_FAILURE_EVENT), ResourceDeleteFailureData.class); - put(canonicalizeEventType(RESOURCE_DELETE_CANCEL_EVENT), ResourceDeleteCancelData.class); - put(canonicalizeEventType(RESOURCE_ACTION_SUCCESS_EVENT), ResourceActionSuccessData.class); - put(canonicalizeEventType(RESOURCE_ACTION_FAILURE_EVENT), ResourceActionFailureData.class); - put(canonicalizeEventType(RESOURCE_ACTION_CANCEL_EVENT), ResourceActionCancelData.class); + put(RESOURCE_WRITE_SUCCESS , ResourceWriteSuccessData.class); + put(RESOURCE_WRITE_FAILURE , ResourceWriteFailureData.class); + put(RESOURCE_WRITE_CANCEL , ResourceWriteCancelData.class); + put(RESOURCE_DELETE_SUCCESS , ResourceDeleteSuccessData.class); + put(RESOURCE_DELETE_FAILURE , ResourceDeleteFailureData.class); + put(RESOURCE_DELETE_CANCEL , ResourceDeleteCancelData.class); + put(RESOURCE_ACTION_SUCCESS , ResourceActionSuccessData.class); + put(RESOURCE_ACTION_FAILURE , ResourceActionFailureData.class); + put(RESOURCE_ACTION_CANCEL , ResourceActionCancelData.class); // // ServiceBus events. - put(canonicalizeEventType(SERVICE_BUS_ACTIVE_MESSAGES_AVAILABLE_WITH_NO_LISTENERS_EVENT), ServiceBusActiveMessagesAvailableWithNoListenersEventData.class); - put(canonicalizeEventType(SERVICE_BUS_DEADLETTER_MESSAGES_AVAILABLE_WITH_NO_LISTENER_EVENT), ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.class); + put(SERVICE_BUS_ACTIVE_MESSAGES_AVAILABLE_WITH_NO_LISTENERS , ServiceBusActiveMessagesAvailableWithNoListenersEventData.class); + put(SERVICE_BUS_DEADLETTER_MESSAGES_AVAILABLE_WITH_NO_LISTENER , ServiceBusDeadletterMessagesAvailableWithNoListenersEventData.class); // // Storage events. - put(canonicalizeEventType(STORAGE_BLOB_CREATED_EVENT), StorageBlobCreatedEventData.class); - put(canonicalizeEventType(STORAGE_BLOB_DELETED_EVENT), StorageBlobDeletedEventData.class); + put(STORAGE_BLOB_CREATED , StorageBlobCreatedEventData.class); + put(STORAGE_BLOB_DELETED , StorageBlobDeletedEventData.class); + put(STORAGE_BLOB_RENAMED , StorageBlobRenamedEventData.class); // Communication service events. - put(canonicalizeEventType(COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER), AcsChatMemberAddedToThreadWithUserEventData.class); - put(canonicalizeEventType(COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER), AcsChatMemberRemovedFromThreadWithUserEventData.class); - put(canonicalizeEventType(COMMUNICATION_CHAT_MESSAGE_DELETED), AcsChatMessageDeletedEventData.class); - put(canonicalizeEventType(COMMUNICATION_CHAT_MESSAGE_EDITED), AcsChatMessageEditedEventData.class); - put(canonicalizeEventType(COMMUNICATION_CHAT_MESSAGE_RECEIVED), AcsChatMessageReceivedEventData.class); - put(canonicalizeEventType(COMMUNICATION_CHAT_THREAD_CREATED_WITH_USER), AcsChatThreadCreatedWithUserEventData.class); - put(canonicalizeEventType(COMMUNICATION_CHAT_THREAD_PROPERTIES_UPDATED_PER_USER), AcsChatThreadPropertiesUpdatedPerUserEventData.class); - put(canonicalizeEventType(COMMUNICATION_CHAT_THREAD_WITH_USER_DELETED), AcsChatThreadWithUserDeletedEventData.class); - put(canonicalizeEventType(COMMUNICATION_SMS_DELIVERY_REPORT_RECEIVED), AcsSmsDeliveryReportReceivedEventData.class); - put(canonicalizeEventType(COMMUNICATION_SMS_RECEIVED), AcsSmsReceivedEventData.class); + put(COMMUNICATION_CHAT_MEMBER_ADDED_TO_THREAD_WITH_USER, AcsChatMemberAddedToThreadWithUserEventData.class); + put(COMMUNICATION_CHAT_MEMBER_REMOVED_FROM_THREAD_WITH_USER, AcsChatMemberRemovedFromThreadWithUserEventData.class); + put(COMMUNICATION_CHAT_MESSAGE_DELETED, AcsChatMessageDeletedEventData.class); + put(COMMUNICATION_CHAT_MESSAGE_EDITED, AcsChatMessageEditedEventData.class); + put(COMMUNICATION_CHAT_MESSAGE_RECEIVED, AcsChatMessageReceivedEventData.class); + put(COMMUNICATION_CHAT_THREAD_CREATED_WITH_USER, AcsChatThreadCreatedWithUserEventData.class); + put(COMMUNICATION_CHAT_THREAD_PROPERTIES_UPDATED_PER_USER, AcsChatThreadPropertiesUpdatedPerUserEventData.class); + put(COMMUNICATION_CHAT_THREAD_WITH_USER_DELETED, AcsChatThreadWithUserDeletedEventData.class); + put(COMMUNICATION_SMS_DELIVERY_REPORT_RECEIVED, AcsSmsDeliveryReportReceivedEventData.class); + put(COMMUNICATION_SMS_RECEIVED, AcsSmsReceivedEventData.class); // Web events - put(canonicalizeEventType(WEB_APP_UPDATED), WebAppUpdatedEventData.class); - put(canonicalizeEventType(WEB_BACKUP_OPERATION_STARTED), WebBackupOperationStartedEventData.class); - put(canonicalizeEventType(WEB_BACKUP_OPERATION_COMPLETED), WebBackupOperationCompletedEventData.class); - put(canonicalizeEventType(WEB_BACKUP_OPERATION_FAILED), WebBackupOperationFailedEventData.class); - put(canonicalizeEventType(WEB_RESTORE_OPERATION_STARTED), WebRestoreOperationStartedEventData.class); - put(canonicalizeEventType(WEB_RESTORE_OPERATION_COMPLETED), WebRestoreOperationCompletedEventData.class); - put(canonicalizeEventType(WEB_RESTORE_OPERATION_FAILED), WebRestoreOperationFailedEventData.class); - put(canonicalizeEventType(WEB_SLOT_SWAP_STARTED), WebSlotSwapStartedEventData.class); - put(canonicalizeEventType(WEB_SLOT_SWAP_COMPLETED), WebSlotSwapCompletedEventData.class); - put(canonicalizeEventType(WEB_SLOT_SWAP_FAILED), WebSlotSwapFailedEventData.class); - put(canonicalizeEventType(WEB_SLOT_SWAP_WITH_PREVIEW_STARTED), WebSlotSwapWithPreviewStartedEventData.class); - put(canonicalizeEventType(WEB_SLOT_SWAP_WITH_PREVIEW_CANCELLED), WebSlotSwapWithPreviewCancelledEventData.class); - put(canonicalizeEventType(WEB_APP_SERVICE_PLAN_UPDATED), WebAppServicePlanUpdatedEventData.class); + put(WEB_APP_UPDATED, WebAppUpdatedEventData.class); + put(WEB_BACKUP_OPERATION_STARTED, WebBackupOperationStartedEventData.class); + put(WEB_BACKUP_OPERATION_COMPLETED, WebBackupOperationCompletedEventData.class); + put(WEB_BACKUP_OPERATION_FAILED, WebBackupOperationFailedEventData.class); + put(WEB_RESTORE_OPERATION_STARTED, WebRestoreOperationStartedEventData.class); + put(WEB_RESTORE_OPERATION_COMPLETED, WebRestoreOperationCompletedEventData.class); + put(WEB_RESTORE_OPERATION_FAILED, WebRestoreOperationFailedEventData.class); + put(WEB_SLOT_SWAP_STARTED, WebSlotSwapStartedEventData.class); + put(WEB_SLOT_SWAP_COMPLETED, WebSlotSwapCompletedEventData.class); + put(WEB_SLOT_SWAP_FAILED, WebSlotSwapFailedEventData.class); + put(WEB_SLOT_SWAP_WITH_PREVIEW_STARTED, WebSlotSwapWithPreviewStartedEventData.class); + put(WEB_SLOT_SWAP_WITH_PREVIEW_CANCELLED, WebSlotSwapWithPreviewCancelledEventData.class); + put(WEB_APP_SERVICE_PLAN_UPDATED, WebAppServicePlanUpdatedEventData.class); // Machine Learning events - put(canonicalizeEventType(MACHINE_LEARNING_DATASET_DRIFT_DETECTED), MachineLearningServicesDatasetDriftDetectedEventData.class); - put(canonicalizeEventType(MACHINE_LEARNING_MODEL_DEPLOYED), MachineLearningServicesModelDeployedEventData.class); - put(canonicalizeEventType(MACHINE_LEARNING_MODEL_REGISTERED), MachineLearningServicesModelRegisteredEventData.class); - put(canonicalizeEventType(MACHINE_LEARNING_RUN_COMPLETED), MachineLearningServicesRunCompletedEventData.class); - put(canonicalizeEventType(MACHINE_LEARNING_RUN_STATUS_CHANGED), MachineLearningServicesRunStatusChangedEventData.class); + put(MACHINE_LEARNING_DATASET_DRIFT_DETECTED, MachineLearningServicesDatasetDriftDetectedEventData.class); + put(MACHINE_LEARNING_MODEL_DEPLOYED, MachineLearningServicesModelDeployedEventData.class); + put(MACHINE_LEARNING_MODEL_REGISTERED, MachineLearningServicesModelRegisteredEventData.class); + put(MACHINE_LEARNING_RUN_COMPLETED, MachineLearningServicesRunCompletedEventData.class); + put(MACHINE_LEARNING_RUN_STATUS_CHANGED, MachineLearningServicesRunStatusChangedEventData.class); // Key Vault events - put(canonicalizeEventType(KEY_VAULT_CERTIFICATE_NEW_VERSION_CREATED), KeyVaultCertificateNewVersionCreatedEventData.class); - put(canonicalizeEventType(KEY_VAULT_CERTIFICATE_NEAR_EXPIRY), KeyVaultCertificateNearExpiryEventData.class); - put(canonicalizeEventType(KEY_VAULT_CERTIFICATE_EXPIRED), KeyVaultCertificateExpiredEventData.class); - put(canonicalizeEventType(KEY_VAULT_KEY_NEW_VERSION_CREATED), KeyVaultKeyNewVersionCreatedEventData.class); - put(canonicalizeEventType(KEY_VAULT_KEY_NEAR_EXPIRY), KeyVaultKeyNearExpiryEventData.class); - put(canonicalizeEventType(KEY_VAULT_KEY_EXPIRED), KeyVaultKeyExpiredEventData.class); - put(canonicalizeEventType(KEY_VAULT_SECRET_NEW_VERSION_CREATED), KeyVaultSecretNewVersionCreatedEventData.class); - put(canonicalizeEventType(KEY_VAULT_SECRET_NEAR_EXPIRY), KeyVaultSecretNearExpiryEventData.class); - put(canonicalizeEventType(KEY_VAULT_SECRET_EXPIRED), KeyVaultSecretExpiredEventData.class); - put(canonicalizeEventType(KEY_VAULT_VAULT_ACCESS_POLICY_CHANGED), KeyVaultAccessPolicyChangedEventData.class); + put(KEY_VAULT_CERTIFICATE_NEW_VERSION_CREATED, KeyVaultCertificateNewVersionCreatedEventData.class); + put(KEY_VAULT_CERTIFICATE_NEAR_EXPIRY, KeyVaultCertificateNearExpiryEventData.class); + put(KEY_VAULT_CERTIFICATE_EXPIRED, KeyVaultCertificateExpiredEventData.class); + put(KEY_VAULT_KEY_NEW_VERSION_CREATED, KeyVaultKeyNewVersionCreatedEventData.class); + put(KEY_VAULT_KEY_NEAR_EXPIRY, KeyVaultKeyNearExpiryEventData.class); + put(KEY_VAULT_KEY_EXPIRED, KeyVaultKeyExpiredEventData.class); + put(KEY_VAULT_SECRET_NEW_VERSION_CREATED, KeyVaultSecretNewVersionCreatedEventData.class); + put(KEY_VAULT_SECRET_NEAR_EXPIRY, KeyVaultSecretNearExpiryEventData.class); + put(KEY_VAULT_SECRET_EXPIRED, KeyVaultSecretExpiredEventData.class); + put(KEY_VAULT_VAULT_ACCESS_POLICY_CHANGED, KeyVaultAccessPolicyChangedEventData.class); }}; - /** - * Turn a given event type string into it's canonical string, used to convert strings - * when they may have been changed to upper/lower case. - * @param eventType the string to canonicalize. - * - * @return the canonicalized version. - */ - public static String canonicalizeEventType(String eventType) { - if (eventType == null) { - return null; - } else { - return eventType.toLowerCase(Locale.ENGLISH); - } - } - /** * Get a mapping of all the system event type strings to their respective class. This is used by default in * the {@link EventGridEvent} and {@link CloudEvent} classes. @@ -577,6 +566,6 @@ public static Map> getSystemEventMappings() { return Collections.unmodifiableMap(systemEventMappings); } - private SystemEventMappings() { + private SystemEventNames() { } } diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/module-info.java b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/module-info.java index de698998b4b4e..f10572619e5c9 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/module-info.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/main/java/module-info.java @@ -3,11 +3,9 @@ module com.azure.messaging.eventgrid { requires transitive com.azure.core; - requires transitive com.azure.core.serializer.json.jackson; exports com.azure.messaging.eventgrid; exports com.azure.messaging.eventgrid.systemevents; - opens com.azure.messaging.eventgrid.implementation; opens com.azure.messaging.eventgrid.implementation.models to com.fasterxml.jackson.databind; opens com.azure.messaging.eventgrid.systemevents to com.fasterxml.jackson.databind; } diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/ClassTime.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/ClassTime.java deleted file mode 100644 index eeaf475ce206e..0000000000000 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/ClassTime.java +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.messaging.eventgrid; - -import java.time.LocalDate; -import java.time.LocalTime; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.util.Random; - -/** - * This class stores some basic information about college classes and the time they start. - */ -public class ClassTime { - - /** - * All the possible departments/subjects for classes. - */ - public enum Department { - MATH, - PHYS, - BIOL, - ENGL, - CSE - } - - private final Department department; - - private final int courseNumber; - - private final OffsetDateTime startTime; - - /** - * Creates a new instance containing information about the department, course number, and start time of the class. - * @param department the department of the class, e.g. MATH. - * @param courseNumber the course number of the class, e.g. 225 or 101. - * @param time the time the class starts today, e.g. 3:15 pm. - */ - public ClassTime(Department department, int courseNumber, OffsetDateTime time) { - this.department = department; - this.courseNumber = courseNumber; - this.startTime = time; - } - - /** - * Creates a random instance of a class, containing a random department, random realistic course number, and a start - * time that is randomly selected from any 15 minute interval from 7:00 am to 6:00 pm today. - * @param random the random element to use to create the class and time. - * @return a random instance of this class and time. - */ - public static ClassTime getRandom(Random random) { - Department department = Department.values()[random.nextInt(Department.values().length)]; - int courseNumber = random.nextInt(500) + 100; - OffsetDateTime time = OffsetDateTime.of(LocalDate.now(), - LocalTime.MIDNIGHT.plusHours(7).plusMinutes(random.nextInt(44) * 15), ZoneOffset.UTC); - return new ClassTime(department, courseNumber, time); - } - - /** - * Get the starting time of this class. - * @return the start time. - */ - public OffsetDateTime getStartTime() { - return startTime; - } - - /** - * Get the department/subject of the class. - * @return the department. - */ - public String getDepartment() { - return department.toString(); - } - - /** - * Get the course number of this class. - * @return the class course number. - */ - public int getCourseNumber() { - return courseNumber; - } - - @Override - public String toString() { - return getDepartment() + " " + getCourseNumber() + " starts at: " + getStartTime().toLocalTime().toString(); - } -} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/PublishClassTime.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/PublishClassTime.java deleted file mode 100644 index bc511143698ec..0000000000000 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/PublishClassTime.java +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.messaging.eventgrid; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.core.util.serializer.JacksonAdapter; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import com.fasterxml.jackson.databind.module.SimpleModule; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -/** - * This Sample is an example of using a custom serializer to send custom event data to an EventGrid topic. - * - * To run this sample, first create an EventGrid topic and store the key and endpoint as system environment variables. - * See the README in the library folder for more help on getting started with EventGrid. - * - * Run the main method with no arguments to start publishing! By the end, you should have published 50 batches of - * events to your topic, with each batch containing a number of individual events. - */ -public class PublishClassTime { - - private static final int REPEATS = 50; - - public static void main(String[] args) throws InterruptedException { - publishEvents(); - } - - public static void publishEvents() throws InterruptedException { - String key = System.getenv("TOPIC_KEY"); - String endpoint = System.getenv("TOPIC_ENDPOINT"); - - JacksonAdapter customSerializer = new JacksonAdapter(); - - customSerializer.serializer().registerModule(new SimpleModule().addSerializer(ClassTime.class, - new JsonSerializer() { - - @Override - public void serialize(ClassTime classTime, JsonGenerator jsonGenerator, - SerializerProvider serializerProvider) throws IOException { - jsonGenerator.writeStartObject(); - jsonGenerator.writeStringField("department", classTime.getDepartment()); - jsonGenerator.writeNumberField("courseNumber", classTime.getCourseNumber()); - jsonGenerator.writeStringField("startTime", classTime.getStartTime().toString()); - jsonGenerator.writeEndObject(); - } - })); - - // EG client - EventGridPublisherClient egClient = new EventGridPublisherClientBuilder() - .credential(new AzureKeyCredential(key)) - .endpoint(endpoint) - .serializer(customSerializer) - .buildClient(); - - Random random = new Random(); - - for (int i = 0; i < REPEATS; i++) { - - publish(egClient, random); - Thread.sleep(1000); - } - - - } - - - public static void publish(EventGridPublisherClient egClient, Random random) { - List events = new ArrayList<>(); - int times = random.nextInt(4) + 1; - for (int i = 0; i < times; i++) { - ClassTime classTime = ClassTime.getRandom(random); - System.out.println(classTime); - - events.add(new CloudEvent("/microsoft/demo", "Microsoft.Demo.ClassTime") - .setData(classTime)); - } - System.out.println(); - - - egClient.sendCloudEvents(events); - } -} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/ReadmeSamples.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/ReadmeSamples.java deleted file mode 100644 index 0493674ecdb5e..0000000000000 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/ReadmeSamples.java +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.messaging.eventgrid; - -import com.azure.core.credential.AzureKeyCredential; -import com.azure.messaging.eventgrid.systemevents.SubscriptionValidationEventData; - -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.List; - -/** - * WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS - * ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING - * LINE NUMBERS OF EXISTING CODE SAMPLES. - *

- * Code samples for the README.md - */ -public class ReadmeSamples { - - private final String endpoint = "endpoint"; - private final String key = "key"; - private final EventGridPublisherClient egClient = new EventGridPublisherClientBuilder().buildClient(); - private final String jsonData = "Json encoded event"; - - public void createPublisherClient() { - EventGridPublisherClient egClient = new EventGridPublisherClientBuilder() - .endpoint(endpoint) - .credential(new AzureKeyCredential(key)) - .buildClient(); - } - - public void createAsyncPublisherClient() { - EventGridPublisherAsyncClient egAsyncClient = new EventGridPublisherClientBuilder() - .endpoint(endpoint) - .credential(new AzureKeyCredential(key)) - .buildAsyncClient(); - } - - public void sendEventGridEvents() { - List events = new ArrayList<>(); - events.add( - new EventGridEvent("exampleSubject", "Com.Example.ExampleEventType", "Example Data", - "1") - ); - - egClient.sendEvents(events); - } - - public void sendCloudEvents() { - List events = new ArrayList<>(); - events.add( - new CloudEvent("com/example/source", "Com.Example.ExampleEventType") - .setData("Example Data") - ); - - egClient.sendCloudEvents(events); - } - - public void consumeEventGridEvent() { - List events = EventGridEvent.parse(jsonData); - - for (EventGridEvent event : events) { - // system event data will be turned into it's rich object, - // while custom event data will be turned into a byte[]. - Object data = event.getData(); - - // this event type goes to any non-azure endpoint (such as a WebHook) when the subscription is created. - if (data instanceof SubscriptionValidationEventData) { - SubscriptionValidationEventData validationData = (SubscriptionValidationEventData) data; - System.out.println(validationData.getValidationCode()); - } else if (data instanceof byte[]) { - // we can turn the data into the correct type by calling this method. - // since we set the data as a string when sending, we pass the String class in to get it back. - String stringData = event.getData(String.class); - System.out.println(stringData); // "Example Data" - } - } - } - - public void consumeCloudEvent() { - List events = CloudEvent.parse(jsonData); - - for (CloudEvent event : events) { - // system event data will be turned into it's rich object, - // while custom event data will be turned into a byte[]. - Object data = event.getData(); - - // this event type goes to any non-azure endpoint (such as a WebHook) when the subscription is created. - if (data instanceof SubscriptionValidationEventData) { - SubscriptionValidationEventData validationData = (SubscriptionValidationEventData) data; - System.out.println(validationData.getValidationCode()); - } else if (data instanceof byte[]) { - // we can turn the data into the correct type by calling this method. - // since we set the data as a string when sending, we pass the String class in to get it back. - String stringData = event.getData(String.class); - System.out.println(stringData); // "Example Data" - } - } - } - - public void createSharedAccessSignature() { - OffsetDateTime expiration = OffsetDateTime.now().plusMinutes(20); - String credentialString = EventGridSasCredential - .createSas(endpoint, expiration, new AzureKeyCredential(key)); - EventGridSasCredential signature = new EventGridSasCredential(credentialString); - } - - -} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/DeserializeEventsFromString.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/DeserializeEventsFromString.java new file mode 100644 index 0000000000000..fc9d79e4b3341 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/DeserializeEventsFromString.java @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid.samples; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.serializer.TypeReference; +import com.azure.messaging.eventgrid.CloudEvent; +import com.azure.messaging.eventgrid.EventGridEvent; +import com.azure.messaging.eventgrid.samples.models.User; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +public class DeserializeEventsFromString { + + private static void deserializeCloudEventsFromJsonString() { + System.out.println("Parsing a Cloud Event string"); + + String cloudEventStringJsonData = "{" + + "\"id\":\"f47d7b0a-4cc7-4108-aaff-f1122d87807c\"," + + "\"source\":\"https://com.example.myapp\"," + + "\"data\":{\"firstName\":\"John1\",\"lastName\":\"James\"}," + + "\"type\":\"User.Created.Object\"," + + "\"specversion\":\"1.0\"," + + "\"datacontenttype\":\"application/json\"" + + "}"; + List cloudEvents = CloudEvent.fromString(cloudEventStringJsonData); + + CloudEvent cloudEvent = cloudEvents.get(0); + + BinaryData data = cloudEvent.getData(); + if (data != null) { + deserializeData(data); + } + } + + private static void deserializeEventGridEventsFromJsonString() { + System.out.println("Parsing an Event Grid Event string"); + + String eventGridEventStringJsonData = "{\"id\":\"3b07dc21-08af-4558-9e94-822a20c48a0b\"," + + "\"subject\":\"example user\"," + + "\"data\":{\"firstName\":\"John2\",\"lastName\":\"James\"}," + + "\"eventType\":\"User.Created.Object\"," + + "\"dataVersion\":\"0.1\"," + + "\"metadataVersion\":\"1\"," + + "\"eventTime\":\"2021-01-12T22:23:38.756238Z\"," + + "\"topic\":\"/exampleTopic\"}\n"; + List eventGridEvents = EventGridEvent.fromString(eventGridEventStringJsonData); + EventGridEvent eventGridEvent = eventGridEvents.get(0); + BinaryData data = eventGridEvent.getData(); + if (data != null) { + deserializeData(data); + } + } + + private static void deserializeData(BinaryData eventData) { + System.out.println("Deserialize data to a model class:"); + User dataInModelClass = eventData.toObject(TypeReference.createInstance(User.class)); + System.out.println(dataInModelClass); + System.out.println(); + + System.out.println("Deserialize data to a Map:"); + Map dataMap = eventData.toObject(TypeReference.createInstance(Map.class)); + System.out.println(dataMap); + System.out.println(); + + System.out.println("Deserialize data to a String:"); + String dataString = eventData.toString(); + System.out.println(dataString); + System.out.println(); + + System.out.println("Deserialize data to byte[]"); + byte[] dataInBytes = eventData.toBytes(); + System.out.println(Arrays.toString(dataInBytes)); + System.out.println(); + } + + public static void main(String[] args) { + deserializeCloudEventsFromJsonString(); + deserializeEventGridEventsFromJsonString(); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/GenerateSasToken.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/GenerateSasToken.java new file mode 100644 index 0000000000000..eed2e049bafca --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/GenerateSasToken.java @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid.samples; + +import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.credential.AzureSasCredential; +import com.azure.messaging.eventgrid.EventGridPublisherClient; +import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder; +import com.azure.messaging.eventgrid.EventGridSasGenerator; + +import java.time.OffsetDateTime; + +public class GenerateSasToken { + public static void main(String[] args) { + // 1. Generate the SAS token. + String sasToken = EventGridSasGenerator.generateSas( + System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"), + new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")), + OffsetDateTime.now().plusMinutes(20)); + System.out.println(sasToken); + + // 2. Use the SAS token to create an client to send events. + // For how to use the client to send events, refer to the Publish* samples in the same folder. + EventGridPublisherClient publisherClient = new EventGridPublisherClientBuilder() + .endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT")) + .credential(new AzureSasCredential(sasToken)) + .buildClient(); + + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/ProcessSystemEvents.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/ProcessSystemEvents.java new file mode 100644 index 0000000000000..d8d8a39ca47a9 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/ProcessSystemEvents.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid.samples; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.serializer.TypeReference; +import com.azure.messaging.eventgrid.EventGridEvent; +import com.azure.messaging.eventgrid.SystemEventNames; +import com.azure.messaging.eventgrid.systemevents.AppConfigurationKeyValueDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.AppConfigurationKeyValueModifiedEventData; + +import java.util.List; + +public class ProcessSystemEvents { + public static void main(String[] args) { + String eventGridJsonString = "[\n" + + " {\n" + + " \"id\": \"56afc886-767b-d359-d59e-0da7877166b2\",\n" + + " \"topic\": \"/SUBSCRIPTIONS/ID/RESOURCEGROUPS/rg/PROVIDERS/MICROSOFT.ContainerRegistry/test1\",\n" + + " \"subject\": \"test1\",\n" + + " \"eventType\": \"Microsoft.AppConfiguration.KeyValueDeleted\",\n" + + " \"eventTime\": \"2018-01-02T19:17:44.4383997Z\",\n" + + " \"data\": {\n" + + " \"key\":\"key1\",\n" + + " \"label\":\"label1\",\n" + + " \"etag\":\"etag1\"\n" + + " },\n" + + " \"dataVersion\": \"\",\n" + + " \"metadataVersion\": \"1\"\n" + + " }\n" + + "]\n"; + + List eventGridEvents = EventGridEvent.fromString(eventGridJsonString); + + for (EventGridEvent eventGridEvent : eventGridEvents) { + BinaryData data = eventGridEvent.getData(); + switch (eventGridEvent.getEventType()) { + case SystemEventNames.APP_CONFIGURATION_KEY_VALUE_DELETED: + AppConfigurationKeyValueDeletedEventData keyValueDeletedEventData = + data.toObject(TypeReference.createInstance(AppConfigurationKeyValueDeletedEventData.class)); + System.out.println("Processing the AppConfigurationKeyValueDeletedEventData..."); + System.out.printf("The key is: %s%n", keyValueDeletedEventData.getKey()); + break; + + case SystemEventNames.APP_CONFIGURATION_KEY_VALUE_MODIFIED: + AppConfigurationKeyValueModifiedEventData keyValueModifiedEventData = + data.toObject(TypeReference.createInstance(AppConfigurationKeyValueModifiedEventData.class)); + System.out.println("Processing the AppConfigurationKeyValueModifiedEventData..."); + System.out.printf("The key is: %s%n", keyValueModifiedEventData.getKey()); + break; + default: + System.out.printf("%s isn't an AppConfiguration event data%n", eventGridEvent.getEventType()); + break; + } + } + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/PublishCloudEventsToTopic.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/PublishCloudEventsToTopic.java new file mode 100644 index 0000000000000..99c7bda96d689 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/PublishCloudEventsToTopic.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid.samples; + +import com.azure.core.credential.AzureKeyCredential; +import com.azure.messaging.eventgrid.CloudEvent; +import com.azure.messaging.eventgrid.EventGridPublisherClient; +import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder; +import com.azure.messaging.eventgrid.samples.models.User; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +/** + * This sample code shows how to send {@link CloudEvent CloudEvents} to an Event Grid Topic that accepts cloud event schema. + * Refer to the CloudEvent schema. + * + * @see PublishEventGridEventsToTopic for a sample to send an Event Grid event. + */ +public class PublishCloudEventsToTopic { + public static void main(String[] args) { + EventGridPublisherClient publisherClient = new EventGridPublisherClientBuilder() + .endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT")) // make sure it accepts CloudEvent + .credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY"))) + .buildClient(); + + // Create a CloudEvent with String data + String str = "FirstName: John1, LastName:James"; + CloudEvent cloudEventJson = new CloudEvent("https://com.example.myapp", "User.Created.Text", str); + + // Create a CloudEvent with Object data + User newUser = new User("John2", "James"); + CloudEvent cloudEventModel = new CloudEvent("https://com.example.myapp", "User.Created.Object", newUser); + // Create a CloudEvent with binary data + byte[] byteSample = "FirstName: John3, LastName: James".getBytes(StandardCharsets.UTF_8); + CloudEvent cloudEventBytes = new CloudEvent("https://com.example.myapp", "User.Created.Binary", byteSample, "bytes"); + + // Send them to the event grid topic altogether. + List events = new ArrayList<>(); + events.add(cloudEventJson); + events.add(cloudEventModel); + events.add(cloudEventBytes.addExtensionAttribute("extension", "value")); + publisherClient.sendCloudEvents(events); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/PublishEventGridEventsToTopic.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/PublishEventGridEventsToTopic.java new file mode 100644 index 0000000000000..a539bd6550ef7 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/PublishEventGridEventsToTopic.java @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid.samples; + +import com.azure.core.credential.AzureKeyCredential; +import com.azure.messaging.eventgrid.EventGridEvent; +import com.azure.messaging.eventgrid.EventGridPublisherClient; +import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder; +import com.azure.messaging.eventgrid.samples.models.User; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +/** + * This sample code shows how to send {@link EventGridEvent EventGridEvents} to an Event Grid Topic that accepts Event Grid event schema. + * Refer to the EventGridEvent schema. + * + * @see PublishCloudEventsToTopic for a sample to send a CloudEvent + */ +public class PublishEventGridEventsToTopic { + public static void main(String[] args) { + EventGridPublisherClient publisherClient = new EventGridPublisherClientBuilder() + .endpoint(System.getenv("AZURE_EVENTGRID_EVENT_ENDPOINT")) // make sure it accepts EventGridEvent + .credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_EVENT_KEY"))) + .buildClient(); + + // Create a CloudEvent with String data + String str = "FirstName: John1, LastName: James"; + EventGridEvent eventJson = new EventGridEvent("com/example/MyApp", "User.Created.Text", null,"0.1"); + // Create a CloudEvent with Object data + User newUser = new User("John2", "James"); + EventGridEvent eventModelClass = new EventGridEvent("com/example/MyApp", "User.Created.Object", newUser, "0.1"); + // Create a CloudEvent with binary data + byte[] byteSample = "FirstName: John3, LastName: James".getBytes(StandardCharsets.UTF_8); + EventGridEvent eventBytes = new EventGridEvent("com/example/MyApp", "User.Created.Binary", byteSample, "0.1"); + // Send them to the event grid topic altogether. + + List events = new ArrayList<>(); + events.add(eventJson); + events.add(eventModelClass); + events.add(eventBytes); + + publisherClient.sendEventGridEvents(events); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/PublishEventsToDomain.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/PublishEventsToDomain.java new file mode 100644 index 0000000000000..42b814b918fd9 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/PublishEventsToDomain.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid.samples; + +import com.azure.core.credential.AzureKeyCredential; +import com.azure.messaging.eventgrid.EventGridEvent; +import com.azure.messaging.eventgrid.EventGridPublisherClient; +import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder; +import com.azure.messaging.eventgrid.samples.models.User; + +import java.util.ArrayList; +import java.util.List; + +public class PublishEventsToDomain { + public static void main(String[] args) { + EventGridPublisherClient publisherClient = new EventGridPublisherClientBuilder() + .endpoint(System.getenv("AZURE_EVENTGRID_DOMAIN_ENDPOINT")) // Event Grid Domain endpoint + .credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_DOMAIN_KEY"))) + .buildClient(); + + User newUser = new User("John2", "James"); + EventGridEvent eventModelClass = new EventGridEvent("A user is created", "User.Created.Object", newUser, "0.1") + .setTopic("usertopic"); // topic must be set when sending to an Event Grid Domain. + + List events = new ArrayList<>(); + events.add(eventModelClass); + publisherClient.sendEventGridEvents(events); + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/ReadmeSamples.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/ReadmeSamples.java new file mode 100644 index 0000000000000..2091f90217d2a --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/ReadmeSamples.java @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid.samples; + +import com.azure.core.credential.AzureKeyCredential; + +import com.azure.core.credential.AzureSasCredential; +import com.azure.core.util.BinaryData; +import com.azure.core.util.serializer.TypeReference; +import com.azure.messaging.eventgrid.CloudEvent; +import com.azure.messaging.eventgrid.EventGridEvent; +import com.azure.messaging.eventgrid.EventGridPublisherAsyncClient; +import com.azure.messaging.eventgrid.EventGridPublisherClient; +import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder; +import com.azure.messaging.eventgrid.EventGridSasGenerator; +import com.azure.messaging.eventgrid.SystemEventNames; +import com.azure.messaging.eventgrid.samples.models.User; +import com.azure.messaging.eventgrid.systemevents.StorageBlobCreatedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageBlobDeletedEventData; +import com.azure.messaging.eventgrid.systemevents.StorageBlobRenamedEventData; +import com.azure.messaging.eventgrid.systemevents.SubscriptionValidationEventData; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; + +/** + * WARNING: MODIFYING THIS FILE WILL REQUIRE CORRESPONDING UPDATES TO README.md FILE. LINE NUMBERS + * ARE USED TO EXTRACT APPROPRIATE CODE SEGMENTS FROM THIS FILE. ADD NEW CODE AT THE BOTTOM TO AVOID CHANGING + * LINE NUMBERS OF EXISTING CODE SAMPLES. + *

+ * Code samples for the README.md + */ +public class ReadmeSamples { + + private final String endpoint = "endpoint"; + private final String key = "key"; + private final EventGridPublisherClient egClient = new EventGridPublisherClientBuilder().buildClient(); + private final String jsonData = "Json encoded event"; + + public void createPublisherClient() { + EventGridPublisherClient egClient = new EventGridPublisherClientBuilder() + .endpoint(endpoint) + .credential(new AzureKeyCredential(key)) + .buildClient(); + } + + public void createAsyncPublisherClient() { + EventGridPublisherAsyncClient egAsyncClient = new EventGridPublisherClientBuilder() + .endpoint(endpoint) + .credential(new AzureKeyCredential(key)) + .buildAsyncClient(); + } + + public void createPublisherClientWithSAS() { + EventGridPublisherClient egClient = new EventGridPublisherClientBuilder() + .endpoint(endpoint) + .credential(new AzureSasCredential(key)) + .buildClient(); + } + + public void createAsyncPublisherClientWithSAS() { + EventGridPublisherAsyncClient egAsyncClient = new EventGridPublisherClientBuilder() + .endpoint(endpoint) + .credential(new AzureSasCredential(key)) + .buildAsyncClient(); + } + + public void sendEventGridEventsToTopic() { + List events = new ArrayList<>(); + User user = new User("John", "James"); + events.add(new EventGridEvent("exampleSubject", "Com.Example.ExampleEventType", user, "1")); + egClient.sendEventGridEvents(events); + } + + public void sendCloudEventsToTopic() { + List events = new ArrayList<>(); + User user = new User("John", "James"); + events.add(new CloudEvent("https://source.example.com", "Com.Example.ExampleEventType", user)); + egClient.sendCloudEvents(events); + } + + public void deserializeEventGridEvent() { + List events = EventGridEvent.fromString(jsonData); + for (EventGridEvent event : events) { + if (event.getEventType().equals(SystemEventNames.EVENT_GRID_SUBSCRIPTION_VALIDATION)) { + SubscriptionValidationEventData validationData = event.getData() + .toObject(TypeReference.createInstance(SubscriptionValidationEventData.class)); + System.out.println(validationData.getValidationCode()); + } + else { + // we can turn the data into the correct type by calling BinaryData.toString(), BinaryData.toObject(), + // or BinaryData.toBytes(). This sample uses toString. + BinaryData binaryData = event.getData(); + if (binaryData != null) { + System.out.println(binaryData.toString()); + } + } + } + } + + public void deserializeCloudEvent() { + List events = CloudEvent.fromString(jsonData); + for (CloudEvent event : events) { + if (event.getType().equals(SystemEventNames.EVENT_GRID_SUBSCRIPTION_VALIDATION)) { + SubscriptionValidationEventData validationData = event.getData() + .toObject(TypeReference.createInstance(SubscriptionValidationEventData.class)); + System.out.println(validationData.getValidationCode()); + } + else { + // we can turn the data into the correct type by calling BinaryData.toString(), BinaryData.toObject(), + // or BinaryData.toBytes(). This sample uses toString. + BinaryData binaryData = event.getData(); + if (binaryData != null) { + System.out.println(binaryData.toString()); // "Example Data" + } + } + } + } + + public void createSharedAccessSignature() { + OffsetDateTime expiration = OffsetDateTime.now().plusMinutes(20); + String sasToken = EventGridSasGenerator + .generateSas(endpoint, new AzureKeyCredential(key), expiration); + } + + public void sendEventGridEventsToDomain() { + List events = new ArrayList<>(); + User user = new User("John", "James"); + events.add( + new EventGridEvent("com/example", "Com.Example.ExampleEventType", user, "1") + .setTopic("yourtopic")); + egClient.sendEventGridEvents(events); + } + + public void systemEventDataSampleCode() { + String eventGridEventJsonData = "Your event grid event Json data"; + List events = EventGridEvent.fromString(eventGridEventJsonData); + EventGridEvent event = events.get(0); + + // Look up the System Event data class + Class eventDataClazz = SystemEventNames.getSystemEventMappings().get(event.getEventType()); + + // Deserialize the event data to an instance of a specific System Event data class type + BinaryData data = event.getData(); + if (data != null) { + StorageBlobCreatedEventData blobCreatedData = data.toObject(TypeReference.createInstance(StorageBlobCreatedEventData.class)); + System.out.println(blobCreatedData.getUrl()); + } + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/ReceiveEventsFromEventHandler.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/ReceiveEventsFromEventHandler.java new file mode 100644 index 0000000000000..27b7c1740ba93 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/ReceiveEventsFromEventHandler.java @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid.samples; + +import com.azure.core.util.BinaryData; +import com.azure.core.util.serializer.TypeReference; +import com.azure.messaging.eventgrid.EventGridEvent; +import com.azure.messaging.eventgrid.samples.models.User; +import com.azure.storage.queue.QueueClient; +import com.azure.storage.queue.QueueClientBuilder; +import com.azure.storage.queue.models.QueueMessageItem; + +import java.util.Base64; +import java.util.List; + +/** + * An Event Grid Domain or Topic Subscription can use other Azure Services such as Event Hubs, Service Bus, + * Storage Queue. This sample uses Storage Queue as the event handler to store the events sent to an Event Grid Topic. + */ +public class ReceiveEventsFromEventHandler { + public static void main(String[] args) { + QueueClient storageQueueClient = new QueueClientBuilder() + .connectionString(System.getenv("AZURE_STORAGE_QUEUE_CONNECTION_STRING")) + .queueName(System.getenv("AZURE_STORAGE_QUEUE_NAME_FOR_EVENTGRID")) + .buildClient(); + + Iterable messages = storageQueueClient.receiveMessages(10); + for (QueueMessageItem messageItem : messages) { + String eventJsonString = new String(Base64.getDecoder().decode(messageItem.getMessageText())); + deserializeAndProcessEvents(eventJsonString); + } + } + + private static void deserializeAndProcessEvents(String eventJsonString) { + // assuming all messages in the queue is of event grid event schema + System.out.println(eventJsonString); + List events = EventGridEvent.fromString(eventJsonString); + + for (EventGridEvent event : events) { + BinaryData eventData = event.getData(); + if (eventData != null) { + User user = eventData.toObject(TypeReference.createInstance(User.class)); + System.out.printf("The received event data is: %s%n", user); + } + } + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/models/User.java b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/models/User.java new file mode 100644 index 0000000000000..7181712a35b49 --- /dev/null +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/samples/java/com/azure/messaging/eventgrid/samples/models/User.java @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventgrid.samples.models; + +public class User { + private String firstName; + private String lastName; + + public User() { + + } + public User(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + @Override + public String toString() { + return "User{" + + "firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + '}'; + } +} diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/DeserializationTests.java b/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/DeserializationTests.java index 4bd5d62f79489..e3aa2867bc12b 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/DeserializationTests.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/DeserializationTests.java @@ -3,6 +3,8 @@ package com.azure.messaging.eventgrid; +import com.azure.core.util.BinaryData; +import com.azure.core.util.serializer.TypeReference; import com.azure.messaging.eventgrid.implementation.models.ContosoItemReceivedEventData; import com.azure.messaging.eventgrid.implementation.models.ContosoItemSentEventData; import com.azure.messaging.eventgrid.implementation.models.DroneShippingInfo; @@ -14,10 +16,10 @@ import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; -import org.apache.commons.io.IOUtils; import org.junit.jupiter.api.Test; import java.io.IOException; +import java.io.InputStream; import java.time.OffsetDateTime; import java.util.Base64; import java.util.List; @@ -26,6 +28,20 @@ import static org.junit.jupiter.api.Assertions.*; public class DeserializationTests { + static Object toSystemEventData(EventGridEvent event) { + return getSystemEventData(event.getData(), event.getEventType()); + } + static Object toSystemEventData(CloudEvent event) { + return getSystemEventData(event.getData(), event.getType()); + } + + static Object getSystemEventData(BinaryData data, String eventType) { + if (SystemEventNames.getSystemEventMappings().containsKey(eventType)) { + return data + .toObject(TypeReference.createInstance(SystemEventNames.getSystemEventMappings().get(eventType))); + } + return null; + } // just test to see if these events can be deserialized @Test @@ -89,11 +105,11 @@ public void consumeStorageBlobDeletedEventWithExtraProperty() throws IOException // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof StorageBlobDeletedEventData); - StorageBlobDeletedEventData eventData = (StorageBlobDeletedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof StorageBlobDeletedEventData); + StorageBlobDeletedEventData eventData = (StorageBlobDeletedEventData) toSystemEventData(events[0]); assertEquals("https://example.blob.core.windows.net/testcontainer/testfile.txt", eventData.getUrl()); } @@ -103,12 +119,12 @@ public void consumeEventGridEventWithoutArrayBrackets() throws IOException { String jsonData = getTestPayloadFromFile("EventGridEventNoArray.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); assertEquals(1, events.length); - assertTrue(events[0].getData() instanceof StorageBlobDeletedEventData); - StorageBlobDeletedEventData eventData = (StorageBlobDeletedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof StorageBlobDeletedEventData); + StorageBlobDeletedEventData eventData = (StorageBlobDeletedEventData) toSystemEventData(events[0]); assertEquals("https://example.blob.core.windows.net/testcontainer/testfile.txt", eventData.getUrl()); } @@ -116,14 +132,13 @@ public void consumeEventGridEventWithoutArrayBrackets() throws IOException { public void consumeCloudEventWithoutArrayBrackets() throws IOException { String jsonData = getTestPayloadFromFile("CloudEventNoArray.json"); - List events = CloudEvent.parse(jsonData); + List events = CloudEvent.fromString(jsonData); assertNotNull(events); assertEquals(1, events.size()); - assertEquals(events.get(0).getSpecVersion(), "1.0"); - - ContosoItemReceivedEventData data = events.get(0).getData(ContosoItemReceivedEventData.class); + ContosoItemReceivedEventData data = events.get(0).getData().toObject( + TypeReference.createInstance(ContosoItemReceivedEventData.class)); assertNotNull(data); assertEquals("512d38b6-c7b8-40c8-89fe-f46f9e9622b6", data.getItemSku()); @@ -140,26 +155,20 @@ public void consumeEventGridEventWithNullData() throws IOException { // using a storageBlobDeletedEvent String jsonData = getTestPayloadFromFile("EventGridNullData.json"); // - - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); - - assertNotNull(events); - assertEquals(1, events.length); - assertNull(events[0].getData()); - assertEquals("/blobServices/default/containers/testcontainer/blobs/testfile.txt", events[0].getSubject()); + assertThrows(IllegalArgumentException.class, () -> { + EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); + }); } @Test public void consumeCloudEventWithNullData() throws IOException { String jsonData = getTestPayloadFromFile("CloudEventNullData.json"); - List events = CloudEvent.parse(jsonData); + List events = CloudEvent.fromString(jsonData); assertNotNull(events); assertEquals(1, events.size()); - assertEquals("1.0", events.get(0).getSpecVersion()); - assertNull(events.get(0).getData()); } @@ -169,14 +178,12 @@ public void consumeCloudEventWithBinaryData() throws IOException { byte[] data = Base64.getDecoder().decode("samplebinarydata"); - List events = CloudEvent.parse(jsonData); + List events = CloudEvent.fromString(jsonData); assertNotNull(events); assertEquals(1, events.size()); - assertEquals(events.get(0).getSpecVersion(), "1.0"); - - byte[] eventData = (byte[]) events.get(0).getData(); + byte[] eventData = events.get(0).getData().toBytes(); assertNotNull(eventData); @@ -187,14 +194,14 @@ public void consumeCloudEventWithBinaryData() throws IOException { public void consumeCloudEvent() throws IOException { String jsonData = getTestPayloadFromFile("CloudEvent.json"); - List events = CloudEvent.parse(jsonData); + List events = CloudEvent.fromString(jsonData); assertNotNull(events); assertEquals(1, events.size()); - assertEquals(events.get(0).getSpecVersion(), "1.0"); - - ContosoItemReceivedEventData data = events.get(0).getData(ContosoItemReceivedEventData.class); + ContosoItemReceivedEventData data = events.get(0).getData().toObject( + TypeReference.createInstance(ContosoItemReceivedEventData.class) + ); assertNotNull(data); assertEquals("512d38b6-c7b8-40c8-89fe-f46f9e9622b6", data.getItemSku()); @@ -211,16 +218,14 @@ public void consumeCloudEvent() throws IOException { public void consumeCloudEventXmlData() throws IOException { String jsonData = getTestPayloadFromFile("CloudEventXmlData.json"); - List events = CloudEvent.parse(jsonData); + List events = CloudEvent.fromString(jsonData); assertNotNull(events); assertEquals(1, events.size()); - assertEquals(events.get(0).getSpecVersion(), "1.0"); - assertEquals(events.get(0).getExtensionAttributes().get("comexampleothervalue"), 5); - String xmlData = events.get(0).getData(String.class); + String xmlData = events.get(0).getData().toString(); assertEquals("", xmlData); } @@ -230,12 +235,12 @@ public void consumeCustomEvents() throws IOException { String jsonData = getTestPayloadFromFile("CustomEvents.json"); - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); assertEquals(1, events.length); - assertNotNull(events[0].getData(ContosoItemReceivedEventData.class)); - ContosoItemReceivedEventData eventData = events[0].getData(ContosoItemReceivedEventData.class); + assertNotNull(events[0].getData().toObject(TypeReference.createInstance(ContosoItemReceivedEventData.class))); + ContosoItemReceivedEventData eventData = events[0].getData().toObject(TypeReference.createInstance(ContosoItemReceivedEventData.class)); assertEquals("512d38b6-c7b8-40c8-89fe-f46f9e9622b6", eventData.getItemSku()); } @@ -245,11 +250,11 @@ public void consumeCustomEventWithArrayData() throws IOException { // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); assertEquals(1, events.length); - ContosoItemReceivedEventData[] eventData = events[0].getData(ContosoItemReceivedEventData[].class); + ContosoItemReceivedEventData[] eventData = events[0].getData().toObject(TypeReference.createInstance(ContosoItemReceivedEventData[].class)); assertNotNull(eventData); assertEquals("512d38b6-c7b8-40c8-89fe-f46f9e9622b6", (eventData[0]).getItemSku()); @@ -260,12 +265,12 @@ public void consumeCustomEventWithBooleanData() throws IOException { String jsonData = getTestPayloadFromFile("CustomEventWithBooleanData.json"); - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); assertEquals(1, events.length); - Boolean eventData = events[0].getData(Boolean.class); + Boolean eventData = events[0].getData().toObject(TypeReference.createInstance(Boolean.class)); assertNotNull(eventData); assertTrue(eventData); @@ -277,12 +282,12 @@ public void consumeCustomEventWithStringData() throws IOException { // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); assertEquals(1, events.length); - String eventData = events[0].getData(String.class); + String eventData = events[0].getData().toString(); assertNotNull(eventData); assertEquals("stringdata", eventData); @@ -293,13 +298,13 @@ public void consumeCustomEventWithPolymorphicData() throws IOException { String jsonData = getTestPayloadFromFile("CustomEventWithPolymorphicData.json"); - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); assertEquals(2, events.length); - ContosoItemSentEventData eventData0 = events[0].getData(ContosoItemSentEventData.class); - ContosoItemSentEventData eventData1 = events[1].getData(ContosoItemSentEventData.class); + ContosoItemSentEventData eventData0 = events[0].getData().toObject(TypeReference.createInstance(ContosoItemSentEventData.class)); + ContosoItemSentEventData eventData1 = events[1].getData().toObject(TypeReference.createInstance(ContosoItemSentEventData.class)); assertNotNull(eventData0); assertNotNull(eventData1); @@ -315,15 +320,15 @@ public void consumeMultipleEventsInSameBatch() throws IOException { String jsonData = getTestPayloadFromFile("MultipleEventsInSameBatch.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); assertEquals(4, events.length); - assertTrue(events[0].getData() instanceof StorageBlobCreatedEventData); - assertTrue(events[1].getData() instanceof StorageBlobDeletedEventData); - assertTrue(events[2].getData() instanceof StorageBlobDeletedEventData); - assertTrue(events[3].getData() instanceof ServiceBusDeadletterMessagesAvailableWithNoListenersEventData); - StorageBlobDeletedEventData eventData = (StorageBlobDeletedEventData) events[2].getData(); + assertTrue(toSystemEventData(events[0]) instanceof StorageBlobCreatedEventData); + assertTrue(toSystemEventData(events[1]) instanceof StorageBlobDeletedEventData); + assertTrue(toSystemEventData(events[2]) instanceof StorageBlobDeletedEventData); + assertTrue(toSystemEventData(events[3]) instanceof ServiceBusDeadletterMessagesAvailableWithNoListenersEventData); + StorageBlobDeletedEventData eventData = (StorageBlobDeletedEventData) toSystemEventData(events[2]); assertEquals("https://example.blob.core.windows.net/testcontainer/testfile.txt", eventData.getUrl()); } @@ -333,11 +338,11 @@ public void consumeAppConfigurationKeyValueDeletedEvent() throws IOException { String jsonData = getTestPayloadFromFile("AppConfigurationKeyValueDeleted.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof AppConfigurationKeyValueDeletedEventData); - AppConfigurationKeyValueDeletedEventData eventData = (AppConfigurationKeyValueDeletedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof AppConfigurationKeyValueDeletedEventData); + AppConfigurationKeyValueDeletedEventData eventData = (AppConfigurationKeyValueDeletedEventData) toSystemEventData(events[0]); assertEquals("key1", eventData.getKey()); } @@ -346,11 +351,11 @@ public void consumeAppConfigurationKeyValueModifiedEvent() throws IOException { String jsonData = getTestPayloadFromFile("AppConfigurationKeyValueModified.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof AppConfigurationKeyValueModifiedEventData); - AppConfigurationKeyValueModifiedEventData eventData = (AppConfigurationKeyValueModifiedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof AppConfigurationKeyValueModifiedEventData); + AppConfigurationKeyValueModifiedEventData eventData = (AppConfigurationKeyValueModifiedEventData) toSystemEventData(events[0]); assertEquals("key1", eventData.getKey()); } @@ -360,11 +365,11 @@ public void consumeContainerRegistryImagePushedEvent() throws IOException { String jsonData = getTestPayloadFromFile("ContainerRegistryImagePushedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ContainerRegistryImagePushedEventData); - ContainerRegistryImagePushedEventData eventData = (ContainerRegistryImagePushedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ContainerRegistryImagePushedEventData); + ContainerRegistryImagePushedEventData eventData = (ContainerRegistryImagePushedEventData) toSystemEventData(events[0]); assertEquals("127.0.0.1", eventData.getRequest().getAddr()); } @@ -373,11 +378,11 @@ public void consumeContainerRegistryImageDeletedEvent() throws IOException { String jsonData = getTestPayloadFromFile("ContainerRegistryImageDeletedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ContainerRegistryImageDeletedEventData); - ContainerRegistryImageDeletedEventData eventData = (ContainerRegistryImageDeletedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ContainerRegistryImageDeletedEventData); + ContainerRegistryImageDeletedEventData eventData = (ContainerRegistryImageDeletedEventData) toSystemEventData(events[0]); assertEquals("testactor", eventData.getActor().getName()); } @@ -386,11 +391,11 @@ public void consumeContainerRegistryChartDeletedEvent() throws IOException { String jsonData = getTestPayloadFromFile("ContainerRegistryChartDeletedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ContainerRegistryChartDeletedEventData); - ContainerRegistryChartDeletedEventData eventData = (ContainerRegistryChartDeletedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ContainerRegistryChartDeletedEventData); + ContainerRegistryChartDeletedEventData eventData = (ContainerRegistryChartDeletedEventData) toSystemEventData(events[0]); assertEquals("mediatype1", eventData.getTarget().getMediaType()); } @@ -399,11 +404,11 @@ public void consumeContainerRegistryChartPushedEvent() throws IOException { String jsonData = getTestPayloadFromFile("ContainerRegistryChartPushedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ContainerRegistryChartPushedEventData); - ContainerRegistryChartPushedEventData eventData = (ContainerRegistryChartPushedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ContainerRegistryChartPushedEventData); + ContainerRegistryChartPushedEventData eventData = (ContainerRegistryChartPushedEventData) toSystemEventData(events[0]); assertEquals("mediatype1", eventData.getTarget().getMediaType()); } @@ -413,11 +418,11 @@ public void consumeIoTHubDeviceCreatedEvent() throws IOException { String jsonData = getTestPayloadFromFile("IoTHubDeviceCreatedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof IotHubDeviceCreatedEventData); - IotHubDeviceCreatedEventData eventData = (IotHubDeviceCreatedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof IotHubDeviceCreatedEventData); + IotHubDeviceCreatedEventData eventData = (IotHubDeviceCreatedEventData) toSystemEventData(events[0]); assertEquals("enabled", eventData.getTwin().getStatus()); } @@ -426,11 +431,11 @@ public void consumeIoTHubDeviceDeletedEvent() throws IOException { String jsonData = getTestPayloadFromFile("IoTHubDeviceDeletedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof IotHubDeviceDeletedEventData); - IotHubDeviceDeletedEventData eventData = (IotHubDeviceDeletedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof IotHubDeviceDeletedEventData); + IotHubDeviceDeletedEventData eventData = (IotHubDeviceDeletedEventData) toSystemEventData(events[0]); assertEquals("AAAAAAAAAAE=", eventData.getTwin().getEtag()); } @@ -439,11 +444,11 @@ public void consumeIoTHubDeviceConnectedEvent() throws IOException { String jsonData = getTestPayloadFromFile("IoTHubDeviceConnectedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof IotHubDeviceConnectedEventData); - IotHubDeviceConnectedEventData eventData = (IotHubDeviceConnectedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof IotHubDeviceConnectedEventData); + IotHubDeviceConnectedEventData eventData = (IotHubDeviceConnectedEventData) toSystemEventData(events[0]); assertEquals("EGTESTHUB1", eventData.getHubName()); } @@ -452,11 +457,11 @@ public void consumeIoTHubDeviceDisconnectedEvent() throws IOException { String jsonData = getTestPayloadFromFile("IoTHubDeviceDisconnectedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof IotHubDeviceDisconnectedEventData); - IotHubDeviceDisconnectedEventData eventData = (IotHubDeviceDisconnectedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof IotHubDeviceDisconnectedEventData); + IotHubDeviceDisconnectedEventData eventData = (IotHubDeviceDisconnectedEventData) toSystemEventData(events[0]); assertEquals("000000000000000001D4132452F67CE200000002000000000000000000000002", eventData.getDeviceConnectionStateEventInfo().getSequenceNumber()); } @@ -465,11 +470,11 @@ public void consumeIoTHubDeviceTelemetryEvent() throws IOException { String jsonData = getTestPayloadFromFile("IoTHubDeviceTelemetryEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof IotHubDeviceTelemetryEventData); - IotHubDeviceTelemetryEventData eventData = (IotHubDeviceTelemetryEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof IotHubDeviceTelemetryEventData); + IotHubDeviceTelemetryEventData eventData = (IotHubDeviceTelemetryEventData) toSystemEventData(events[0]); assertEquals("Active", eventData.getProperties().get("Status")); } @@ -479,11 +484,11 @@ public void consumeEventGridSubscriptionValidationEvent() throws IOException { String jsonData = getTestPayloadFromFile("EventGridSubscriptionValidationEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof SubscriptionValidationEventData); - SubscriptionValidationEventData eventData = (SubscriptionValidationEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof SubscriptionValidationEventData); + SubscriptionValidationEventData eventData = (SubscriptionValidationEventData) toSystemEventData(events[0]); assertEquals("512d38b6-c7b8-40c8-89fe-f46f9e9622b6", eventData.getValidationCode()); } @@ -492,11 +497,11 @@ public void consumeEventGridSubscriptionDeletedEvent() throws IOException { String jsonData = getTestPayloadFromFile("EventGridSubscriptionDeletedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof SubscriptionDeletedEventData); - SubscriptionDeletedEventData eventData = (SubscriptionDeletedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof SubscriptionDeletedEventData); + SubscriptionDeletedEventData eventData = (SubscriptionDeletedEventData) toSystemEventData(events[0]); assertEquals("/subscriptions/id/resourceGroups/rg/providers/Microsoft.EventGrid/topics/topic1/providers/Microsoft.EventGrid/eventSubscriptions/eventsubscription1", eventData.getEventSubscriptionId()); } @@ -506,11 +511,11 @@ public void consumeEventHubCaptureFileCreatedEvent() throws IOException { String jsonData = getTestPayloadFromFile("EventHubCaptureFileCreatedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof EventHubCaptureFileCreatedEventData); - EventHubCaptureFileCreatedEventData eventData = (EventHubCaptureFileCreatedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof EventHubCaptureFileCreatedEventData); + EventHubCaptureFileCreatedEventData eventData = (EventHubCaptureFileCreatedEventData) toSystemEventData(events[0]); assertEquals("AzureBlockBlob", eventData.getFileType()); } @@ -520,11 +525,11 @@ public void consumeMapsGeoFenceEnteredEvent() throws IOException { String jsonData = getTestPayloadFromFile("MapsGeofenceEnteredEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MapsGeofenceEnteredEventData); - MapsGeofenceEnteredEventData eventData = (MapsGeofenceEnteredEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MapsGeofenceEnteredEventData); + MapsGeofenceEnteredEventData eventData = (MapsGeofenceEnteredEventData) toSystemEventData(events[0]); assertEquals(true, eventData.isEventPublished()); } @@ -533,11 +538,11 @@ public void consumeMapsGeoFenceExitedEvent() throws IOException { String jsonData = getTestPayloadFromFile("MapsGeofenceExitedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MapsGeofenceExitedEventData); - MapsGeofenceExitedEventData eventData = (MapsGeofenceExitedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MapsGeofenceExitedEventData); + MapsGeofenceExitedEventData eventData = (MapsGeofenceExitedEventData) toSystemEventData(events[0]); assertEquals(true, eventData.isEventPublished()); } @@ -546,11 +551,11 @@ public void consumeMapsGeoFenceResultEvent() throws IOException { String jsonData = getTestPayloadFromFile("MapsGeofenceResultEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MapsGeofenceResultEventData); - MapsGeofenceResultEventData eventData = (MapsGeofenceResultEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MapsGeofenceResultEventData); + MapsGeofenceResultEventData eventData = (MapsGeofenceResultEventData) toSystemEventData(events[0]); assertEquals(true, eventData.isEventPublished()); } @@ -560,11 +565,11 @@ public void consumeMediaJobCanceledEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobCanceledEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobCanceledEventData); - MediaJobCanceledEventData eventData = (MediaJobCanceledEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobCanceledEventData); + MediaJobCanceledEventData eventData = (MediaJobCanceledEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.CANCELING, eventData.getPreviousState()); assertEquals(MediaJobState.CANCELED, eventData.getState()); assertEquals(1, eventData.getOutputs().size()); @@ -583,11 +588,11 @@ public void consumeMediaJobCancelingEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobCancelingEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobCancelingEventData); - MediaJobCancelingEventData eventData = (MediaJobCancelingEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobCancelingEventData); + MediaJobCancelingEventData eventData = (MediaJobCancelingEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.PROCESSING, eventData.getPreviousState()); assertEquals(MediaJobState.CANCELING, eventData.getState()); } @@ -597,11 +602,11 @@ public void consumeMediaJobProcessingEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobProcessingEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobProcessingEventData); - MediaJobProcessingEventData eventData = (MediaJobProcessingEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobProcessingEventData); + MediaJobProcessingEventData eventData = (MediaJobProcessingEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.SCHEDULED, eventData.getPreviousState()); assertEquals(MediaJobState.PROCESSING, eventData.getState()); } @@ -611,11 +616,10 @@ public void consumeMediaJobFinishedEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobFinishedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); - + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobFinishedEventData); - MediaJobFinishedEventData eventData = (MediaJobFinishedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobFinishedEventData); + MediaJobFinishedEventData eventData = (MediaJobFinishedEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.PROCESSING, eventData.getPreviousState()); assertEquals(MediaJobState.FINISHED, eventData.getState()); assertEquals(1, eventData.getOutputs().size()); @@ -633,11 +637,11 @@ public void consumeMediaJobErroredEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobErroredEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobErroredEventData); - MediaJobErroredEventData eventData = (MediaJobErroredEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobErroredEventData); + MediaJobErroredEventData eventData = (MediaJobErroredEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.PROCESSING, eventData.getPreviousState()); assertEquals(MediaJobState.ERROR, eventData.getState()); assertEquals(1, eventData.getOutputs().size()); @@ -654,11 +658,11 @@ public void consumeMediaJobOutputStateChangeEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobOutputStateChangeEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobOutputStateChangeEventData); - MediaJobOutputStateChangeEventData eventData = (MediaJobOutputStateChangeEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobOutputStateChangeEventData); + MediaJobOutputStateChangeEventData eventData = (MediaJobOutputStateChangeEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.SCHEDULED, eventData.getPreviousState()); assertEquals(MediaJobState.PROCESSING, eventData.getOutput().getState()); assertTrue(eventData.getOutput() instanceof MediaJobOutputAsset); @@ -671,11 +675,11 @@ public void consumeMediaJobScheduledEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobScheduledEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobScheduledEventData); - MediaJobScheduledEventData eventData = (MediaJobScheduledEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobScheduledEventData); + MediaJobScheduledEventData eventData = (MediaJobScheduledEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.QUEUED, eventData.getPreviousState()); assertEquals(MediaJobState.SCHEDULED, eventData.getState()); } @@ -685,11 +689,11 @@ public void consumeMediaJobOutputCanceledEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobOutputCanceledEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobOutputCanceledEventData); - MediaJobOutputCanceledEventData eventData = (MediaJobOutputCanceledEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobOutputCanceledEventData); + MediaJobOutputCanceledEventData eventData = (MediaJobOutputCanceledEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.CANCELING, eventData.getPreviousState()); assertEquals(MediaJobState.CANCELED, eventData.getOutput().getState()); assertTrue(eventData.getOutput() instanceof MediaJobOutputAsset); @@ -700,11 +704,11 @@ public void consumeMediaJobOutputCancelingEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobOutputCancelingEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobOutputCancelingEventData); - MediaJobOutputCancelingEventData eventData = (MediaJobOutputCancelingEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobOutputCancelingEventData); + MediaJobOutputCancelingEventData eventData = (MediaJobOutputCancelingEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.PROCESSING, eventData.getPreviousState()); assertEquals(MediaJobState.CANCELING, eventData.getOutput().getState()); assertTrue(eventData.getOutput() instanceof MediaJobOutputAsset); @@ -715,11 +719,11 @@ public void consumeMediaJobOutputErroredEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobOutputErroredEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobOutputErroredEventData); - MediaJobOutputErroredEventData eventData = (MediaJobOutputErroredEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobOutputErroredEventData); + MediaJobOutputErroredEventData eventData = (MediaJobOutputErroredEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.PROCESSING, eventData.getPreviousState()); assertEquals(MediaJobState.ERROR, eventData.getOutput().getState()); assertTrue(eventData.getOutput() instanceof MediaJobOutputAsset); @@ -733,11 +737,11 @@ public void consumeMediaJobOutputFinishedEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobOutputFinishedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobOutputFinishedEventData); - MediaJobOutputFinishedEventData eventData = (MediaJobOutputFinishedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobOutputFinishedEventData); + MediaJobOutputFinishedEventData eventData = (MediaJobOutputFinishedEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.PROCESSING, eventData.getPreviousState()); assertEquals(MediaJobState.FINISHED, eventData.getOutput().getState()); assertTrue(eventData.getOutput() instanceof MediaJobOutputAsset); @@ -752,11 +756,11 @@ public void consumeMediaJobOutputProcessingEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobOutputProcessingEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobOutputProcessingEventData); - MediaJobOutputProcessingEventData eventData = (MediaJobOutputProcessingEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobOutputProcessingEventData); + MediaJobOutputProcessingEventData eventData = (MediaJobOutputProcessingEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.SCHEDULED, eventData.getPreviousState()); assertEquals(MediaJobState.PROCESSING, eventData.getOutput().getState()); assertTrue(eventData.getOutput() instanceof MediaJobOutputAsset); @@ -767,11 +771,11 @@ public void consumeMediaJobOutputScheduledEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobOutputScheduledEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobOutputScheduledEventData); - MediaJobOutputScheduledEventData eventData = (MediaJobOutputScheduledEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobOutputScheduledEventData); + MediaJobOutputScheduledEventData eventData = (MediaJobOutputScheduledEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.QUEUED, eventData.getPreviousState()); assertEquals(MediaJobState.SCHEDULED, eventData.getOutput().getState()); assertTrue(eventData.getOutput() instanceof MediaJobOutputAsset); @@ -782,11 +786,11 @@ public void consumeMediaJobOutputProgressEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobOutputProgressEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobOutputProgressEventData); - MediaJobOutputProgressEventData eventData = (MediaJobOutputProgressEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobOutputProgressEventData); + MediaJobOutputProgressEventData eventData = (MediaJobOutputProgressEventData) toSystemEventData(events[0]); assertEquals("TestLabel", eventData.getLabel()); assertTrue(eventData.getJobCorrelationData().containsKey("Field1")); assertEquals("test1", eventData.getJobCorrelationData().get("Field1")); @@ -799,11 +803,11 @@ public void consumeMediaJobStateChangeEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaJobStateChangeEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaJobStateChangeEventData); - MediaJobStateChangeEventData eventData = (MediaJobStateChangeEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaJobStateChangeEventData); + MediaJobStateChangeEventData eventData = (MediaJobStateChangeEventData) toSystemEventData(events[0]); assertEquals(MediaJobState.SCHEDULED, eventData.getPreviousState()); assertEquals(MediaJobState.PROCESSING, eventData.getState()); } @@ -813,11 +817,11 @@ public void consumeMediaLiveEventEncoderConnectedEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaLiveEventEncoderConnectedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaLiveEventEncoderConnectedEventData); - MediaLiveEventEncoderConnectedEventData eventData = (MediaLiveEventEncoderConnectedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaLiveEventEncoderConnectedEventData); + MediaLiveEventEncoderConnectedEventData eventData = (MediaLiveEventEncoderConnectedEventData) toSystemEventData(events[0]); assertEquals("rtmp://liveevent-ec9d26a8.channel.media.azure.net:1935/live/cb5540b10a5646218c1328be95050c59", eventData.getIngestUrl()); assertEquals("Mystream1", eventData.getStreamId()); assertEquals("", eventData.getEncoderIp()); @@ -829,11 +833,11 @@ public void consumeMediaLiveEventConnectionRejectedEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaLiveEventConnectionRejectedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaLiveEventConnectionRejectedEventData); - MediaLiveEventConnectionRejectedEventData eventData = (MediaLiveEventConnectionRejectedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaLiveEventConnectionRejectedEventData); + MediaLiveEventConnectionRejectedEventData eventData = (MediaLiveEventConnectionRejectedEventData) toSystemEventData(events[0]); assertEquals("Mystream1", eventData.getStreamId()); } @@ -842,11 +846,11 @@ public void consumeMediaLiveEventEncoderDisconnectedEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaLiveEventEncoderDisconnectedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaLiveEventEncoderDisconnectedEventData); - MediaLiveEventEncoderDisconnectedEventData eventData = (MediaLiveEventEncoderDisconnectedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaLiveEventEncoderDisconnectedEventData); + MediaLiveEventEncoderDisconnectedEventData eventData = (MediaLiveEventEncoderDisconnectedEventData) toSystemEventData(events[0]); assertEquals("rtmp://liveevent-ec9d26a8.channel.media.azure.net:1935/live/cb5540b10a5646218c1328be95050c59", eventData.getIngestUrl()); assertEquals("Mystream1", eventData.getStreamId()); assertEquals("", eventData.getEncoderIp()); @@ -858,11 +862,11 @@ public void consumeMediaLiveEventIncomingStreamReceivedEvent() throws IOExceptio String jsonData = getTestPayloadFromFile("MediaLiveEventIncomingStreamReceivedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaLiveEventIncomingStreamReceivedEventData); - MediaLiveEventIncomingStreamReceivedEventData eventData = (MediaLiveEventIncomingStreamReceivedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaLiveEventIncomingStreamReceivedEventData); + MediaLiveEventIncomingStreamReceivedEventData eventData = (MediaLiveEventIncomingStreamReceivedEventData) toSystemEventData(events[0]); assertEquals("rtmp://liveevent-ec9d26a8.channel.media.azure.net:1935/live/cb5540b10a5646218c1328be95050c59", eventData.getIngestUrl()); assertEquals("", eventData.getEncoderIp()); assertEquals("3557", eventData.getEncoderPort()); @@ -879,11 +883,11 @@ public void consumeMediaLiveEventIncomingStreamsOutOfSyncEvent() throws IOExcept String jsonData = getTestPayloadFromFile("MediaLiveEventIncomingStreamsOutOfSyncEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaLiveEventIncomingStreamsOutOfSyncEventData); - MediaLiveEventIncomingStreamsOutOfSyncEventData eventData = (MediaLiveEventIncomingStreamsOutOfSyncEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaLiveEventIncomingStreamsOutOfSyncEventData); + MediaLiveEventIncomingStreamsOutOfSyncEventData eventData = (MediaLiveEventIncomingStreamsOutOfSyncEventData) toSystemEventData(events[0]); assertEquals("10999", eventData.getMinLastTimestamp()); assertEquals("video", eventData.getTypeOfStreamWithMinLastTimestamp()); assertEquals("100999", eventData.getMaxLastTimestamp()); @@ -897,11 +901,11 @@ public void consumeMediaLiveEventIncomingVideoStreamsOutOfSyncEvent() throws IOE String jsonData = getTestPayloadFromFile("MediaLiveEventIncomingVideoStreamsOutOfSyncEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaLiveEventIncomingVideoStreamsOutOfSyncEventData); - MediaLiveEventIncomingVideoStreamsOutOfSyncEventData eventData = (MediaLiveEventIncomingVideoStreamsOutOfSyncEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaLiveEventIncomingVideoStreamsOutOfSyncEventData); + MediaLiveEventIncomingVideoStreamsOutOfSyncEventData eventData = (MediaLiveEventIncomingVideoStreamsOutOfSyncEventData) toSystemEventData(events[0]); assertEquals("10999", eventData.getFirstTimestamp()); assertEquals("2000", eventData.getFirstDuration()); assertEquals("100999", eventData.getSecondTimestamp()); @@ -914,11 +918,11 @@ public void consumeMediaLiveEventIncomingDataChunkDroppedEvent() throws IOExcept String jsonData = getTestPayloadFromFile("MediaLiveEventIncomingDataChunkDroppedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaLiveEventIncomingDataChunkDroppedEventData); - MediaLiveEventIncomingDataChunkDroppedEventData eventData = (MediaLiveEventIncomingDataChunkDroppedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaLiveEventIncomingDataChunkDroppedEventData); + MediaLiveEventIncomingDataChunkDroppedEventData eventData = (MediaLiveEventIncomingDataChunkDroppedEventData) toSystemEventData(events[0]); assertEquals("8999", eventData.getTimestamp()); assertEquals("video", eventData.getTrackType()); assertEquals("video1", eventData.getTrackName()); @@ -931,11 +935,11 @@ public void consumeMediaLiveEventIngestHeartbeatEvent() throws IOException { String jsonData = getTestPayloadFromFile("MediaLiveEventIngestHeartbeatEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaLiveEventIngestHeartbeatEventData); - MediaLiveEventIngestHeartbeatEventData eventData = (MediaLiveEventIngestHeartbeatEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaLiveEventIngestHeartbeatEventData); + MediaLiveEventIngestHeartbeatEventData eventData = (MediaLiveEventIngestHeartbeatEventData) toSystemEventData(events[0]); assertEquals("video", eventData.getTrackType()); assertEquals("video", eventData.getTrackName()); assertEquals("11999", eventData.getLastTimestamp()); @@ -950,11 +954,11 @@ public void consumeMediaLiveEventTrackDiscontinuityDetectedEvent() throws IOExce String jsonData = getTestPayloadFromFile("MediaLiveEventTrackDiscontinuityDetectedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof MediaLiveEventTrackDiscontinuityDetectedEventData); - MediaLiveEventTrackDiscontinuityDetectedEventData eventData = (MediaLiveEventTrackDiscontinuityDetectedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof MediaLiveEventTrackDiscontinuityDetectedEventData); + MediaLiveEventTrackDiscontinuityDetectedEventData eventData = (MediaLiveEventTrackDiscontinuityDetectedEventData) toSystemEventData(events[0]); assertEquals("video", eventData.getTrackType()); assertEquals("video", eventData.getTrackName()); assertEquals("10999", eventData.getPreviousTimestamp()); @@ -969,11 +973,11 @@ public void consumeResourceWriteFailureEvent() throws IOException { String jsonData = getTestPayloadFromFile("ResourceWriteFailureEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ResourceWriteFailureData); - ResourceWriteFailureData eventData = (ResourceWriteFailureData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ResourceWriteFailureData); + ResourceWriteFailureData eventData = (ResourceWriteFailureData) toSystemEventData(events[0]); assertEquals("72f988bf-86f1-41af-91ab-2d7cd011db47", eventData.getTenantId()); } @@ -982,11 +986,11 @@ public void consumeResourceWriteCancelEvent() throws IOException { String jsonData = getTestPayloadFromFile("ResourceWriteCancelEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ResourceWriteCancelData); - ResourceWriteCancelData eventData = (ResourceWriteCancelData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ResourceWriteCancelData); + ResourceWriteCancelData eventData = (ResourceWriteCancelData) toSystemEventData(events[0]); assertEquals("72f988bf-86f1-41af-91ab-2d7cd011db47", eventData.getTenantId()); } @@ -995,11 +999,11 @@ public void consumeResourceDeleteSuccessEvent() throws IOException { String jsonData = getTestPayloadFromFile("ResourceDeleteSuccessEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ResourceDeleteSuccessData); - ResourceDeleteSuccessData eventData = (ResourceDeleteSuccessData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ResourceDeleteSuccessData); + ResourceDeleteSuccessData eventData = (ResourceDeleteSuccessData) toSystemEventData(events[0]); assertEquals("72f988bf-86f1-41af-91ab-2d7cd011db47", eventData.getTenantId()); } @@ -1008,11 +1012,11 @@ public void consumeResourceDeleteFailureEvent() throws IOException { String jsonData = getTestPayloadFromFile("ResourceDeleteFailureEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ResourceDeleteFailureData); - ResourceDeleteFailureData eventData = (ResourceDeleteFailureData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ResourceDeleteFailureData); + ResourceDeleteFailureData eventData = (ResourceDeleteFailureData) toSystemEventData(events[0]); assertEquals("72f988bf-86f1-41af-91ab-2d7cd011db47", eventData.getTenantId()); } @@ -1021,11 +1025,11 @@ public void consumeResourceDeleteCancelEvent() throws IOException { String jsonData = getTestPayloadFromFile("ResourceDeleteCancelEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ResourceDeleteCancelData); - ResourceDeleteCancelData eventData = (ResourceDeleteCancelData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ResourceDeleteCancelData); + ResourceDeleteCancelData eventData = (ResourceDeleteCancelData) toSystemEventData(events[0]); assertEquals("72f988bf-86f1-41af-91ab-2d7cd011db47", eventData.getTenantId()); } @@ -1034,11 +1038,11 @@ public void consumeResourceActionSuccessEvent() throws IOException { String jsonData = getTestPayloadFromFile("ResourceActionSuccessEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ResourceActionSuccessData); - ResourceActionSuccessData eventData = (ResourceActionSuccessData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ResourceActionSuccessData); + ResourceActionSuccessData eventData = (ResourceActionSuccessData) toSystemEventData(events[0]); assertEquals("72f988bf-86f1-41af-91ab-2d7cd011db47", eventData.getTenantId()); } @@ -1047,11 +1051,11 @@ public void consumeResourceActionFailureEvent() throws IOException { String jsonData = getTestPayloadFromFile("ResourceActionFailureEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ResourceActionFailureData); - ResourceActionFailureData eventData = (ResourceActionFailureData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ResourceActionFailureData); + ResourceActionFailureData eventData = (ResourceActionFailureData) toSystemEventData(events[0]); assertEquals("72f988bf-86f1-41af-91ab-2d7cd011db47", eventData.getTenantId()); } @@ -1060,11 +1064,11 @@ public void consumeResourceActionCancelEvent() throws IOException { String jsonData = getTestPayloadFromFile("ResourceActionCancelEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ResourceActionCancelData); - ResourceActionCancelData eventData = (ResourceActionCancelData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ResourceActionCancelData); + ResourceActionCancelData eventData = (ResourceActionCancelData) toSystemEventData(events[0]); assertEquals("72f988bf-86f1-41af-91ab-2d7cd011db47", eventData.getTenantId()); } @@ -1074,11 +1078,11 @@ public void consumeServiceBusActiveMessagesAvailableWithNoListenersEvent() throw String jsonData = getTestPayloadFromFile("ServiceBusActiveMessagesAvailableWithNoListenersEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ServiceBusActiveMessagesAvailableWithNoListenersEventData); - ServiceBusActiveMessagesAvailableWithNoListenersEventData eventData = (ServiceBusActiveMessagesAvailableWithNoListenersEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ServiceBusActiveMessagesAvailableWithNoListenersEventData); + ServiceBusActiveMessagesAvailableWithNoListenersEventData eventData = (ServiceBusActiveMessagesAvailableWithNoListenersEventData) toSystemEventData(events[0]); assertEquals("testns1", eventData.getNamespaceName()); } @@ -1087,11 +1091,11 @@ public void consumeServiceBusDeadletterMessagesAvailableWithNoListenersEvent() t String jsonData = getTestPayloadFromFile("ServiceBusDeadletterMessagesAvailableWithNoListenersEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ServiceBusDeadletterMessagesAvailableWithNoListenersEventData); - ServiceBusDeadletterMessagesAvailableWithNoListenersEventData eventData = (ServiceBusDeadletterMessagesAvailableWithNoListenersEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ServiceBusDeadletterMessagesAvailableWithNoListenersEventData); + ServiceBusDeadletterMessagesAvailableWithNoListenersEventData eventData = (ServiceBusDeadletterMessagesAvailableWithNoListenersEventData) toSystemEventData(events[0]); assertEquals("testns1", eventData.getNamespaceName()); } @@ -1101,11 +1105,11 @@ public void consumeStorageBlobCreatedEvent() throws IOException { String jsonData = getTestPayloadFromFile("StorageBlobCreatedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof StorageBlobCreatedEventData); - StorageBlobCreatedEventData eventData = (StorageBlobCreatedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof StorageBlobCreatedEventData); + StorageBlobCreatedEventData eventData = (StorageBlobCreatedEventData) toSystemEventData(events[0]); assertEquals("https://myaccount.blob.core.windows.net/testcontainer/file1.txt", eventData.getUrl()); } @@ -1114,11 +1118,11 @@ public void consumeStorageBlobDeletedEvent() throws IOException { String jsonData = getTestPayloadFromFile("StorageBlobDeletedEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof StorageBlobDeletedEventData); - StorageBlobDeletedEventData eventData = (StorageBlobDeletedEventData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof StorageBlobDeletedEventData); + StorageBlobDeletedEventData eventData = (StorageBlobDeletedEventData) toSystemEventData(events[0]); assertEquals("https://example.blob.core.windows.net/testcontainer/testfile.txt", eventData.getUrl()); } @@ -1128,11 +1132,11 @@ public void consumeResourceWriteSuccessEvent() throws IOException { String jsonData = getTestPayloadFromFile("ResourceWriteSuccessEvent.json"); // - EventGridEvent[] events = EventGridEvent.parse(jsonData).toArray(new EventGridEvent[0]); + EventGridEvent[] events = EventGridEvent.fromString(jsonData).toArray(new EventGridEvent[0]); assertNotNull(events); - assertTrue(events[0].getData() instanceof ResourceWriteSuccessData); - ResourceWriteSuccessData eventData = (ResourceWriteSuccessData) events[0].getData(); + assertTrue(toSystemEventData(events[0]) instanceof ResourceWriteSuccessData); + ResourceWriteSuccessData eventData = (ResourceWriteSuccessData) toSystemEventData(events[0]); assertEquals("72f988bf-86f1-41af-91ab-2d7cd011db47", eventData.getTenantId()); } @@ -1140,7 +1144,10 @@ public void consumeResourceWriteSuccessEvent() throws IOException { private String getTestPayloadFromFile(String fileName) throws IOException { ClassLoader classLoader = getClass().getClassLoader(); - byte[] bytes = IOUtils.toByteArray(classLoader.getResourceAsStream("customization/" + fileName)); - return new String(bytes); + try (InputStream inputStream = classLoader.getResourceAsStream("customization/" + fileName)) { + byte[] bytes = new byte[inputStream.available()]; + inputStream.read(bytes); + return new String(bytes); + } } } diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/EventGridPublisherClientTests.java b/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/EventGridPublisherClientTests.java index ded47df469e32..7722ddf1e0d3d 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/EventGridPublisherClientTests.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/EventGridPublisherClientTests.java @@ -5,6 +5,7 @@ import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.credential.AzureSasCredential; import com.azure.core.http.policy.RetryPolicy; import com.azure.core.http.rest.Response; import com.azure.core.test.TestBase; @@ -14,6 +15,7 @@ import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import reactor.test.StepVerifier; @@ -34,19 +36,19 @@ public class EventGridPublisherClientTests extends TestBase { private EventGridPublisherClientBuilder builder; // Event Grid endpoint for a topic accepting EventGrid schema events - private static final String EVENTGRID_ENDPOINT = "AZURE_EVENTGRID_EVENTGRID_ENDPOINT"; + private static final String EVENTGRID_ENDPOINT = "AZURE_EVENTGRID_EVENT_ENDPOINT"; // Event Grid endpoint for a topic accepting CloudEvents schema events - private static final String CLOUD_ENDPOINT = "AZURE_EVENTGRID_CLOUD_ENDPOINT"; + private static final String CLOUD_ENDPOINT = "AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"; // Event Grid endpoint for a topic accepting custom schema events private static final String CUSTOM_ENDPOINT = "AZURE_EVENTGRID_CUSTOM_ENDPOINT"; // Event Grid access key for a topic accepting EventGrid schema events - private static final String EVENTGRID_KEY = "AZURE_EVENTGRID_EVENTGRID_KEY"; + private static final String EVENTGRID_KEY = "AZURE_EVENTGRID_EVENT_KEY"; // Event Grid access key for a topic accepting CloudEvents schema events - private static final String CLOUD_KEY = "AZURE_EVENTGRID_CLOUD_KEY"; + private static final String CLOUD_KEY = "AZURE_EVENTGRID_CLOUDEVENT_KEY"; // Event Grid access key for a topic accepting custom schema events private static final String CUSTOM_KEY = "AZURE_EVENTGRID_CUSTOM_KEY"; @@ -92,21 +94,21 @@ public void publishEventGridEvents() { "1.0") .setEventTime(OffsetDateTime.now())); - StepVerifier.create(egClient.sendEventsWithResponse(events)) + StepVerifier.create(egClient.sendEventGridEventsWithResponse(events)) .expectNextMatches(voidResponse -> voidResponse.getStatusCode() == 200) .verifyComplete(); } @Test public void publishWithSasToken() { - String sasToken = EventGridSasCredential.createSas( + String sasToken = EventGridSasGenerator.generateSas( getEndpoint(EVENTGRID_ENDPOINT), - OffsetDateTime.now().plusMinutes(20), - getKey(EVENTGRID_KEY) + getKey(EVENTGRID_KEY), + OffsetDateTime.now().plusMinutes(20) ); EventGridPublisherAsyncClient egClient = builder - .credential(new EventGridSasCredential(sasToken)) + .credential(new AzureSasCredential(sasToken)) .endpoint(getEndpoint(EVENTGRID_ENDPOINT)) .buildAsyncClient(); @@ -120,7 +122,7 @@ public void publishWithSasToken() { "1.0") .setEventTime(OffsetDateTime.now())); - StepVerifier.create(egClient.sendEventsWithResponse(events)) + StepVerifier.create(egClient.sendEventGridEventsWithResponse(events)) .expectNextMatches(voidResponse -> voidResponse.getStatusCode() == 200) .verifyComplete(); } @@ -133,13 +135,13 @@ public void publishCloudEvents() { .buildAsyncClient(); List events = new ArrayList<>(); - events.add(new CloudEvent("/microsoft/testEvent", "Microsoft.MockPublisher.TestEvent") - .setSubject("Test") - .setData(new HashMap() {{ + events.add(new CloudEvent("/microsoft/testEvent", "Microsoft.MockPublisher.TestEvent", + new HashMap() {{ put("Field1", "Value1"); put("Field2", "Value2"); put("Field3", "Value3"); }}) + .setSubject("Test") .setTime(OffsetDateTime.now())); StepVerifier.create(egClient.sendCloudEventsWithResponse(events)) @@ -161,6 +163,7 @@ public String getName() { } } + @Disabled @Test public void publishCloudEventsCustomSerializer() { // Custom Serializer for testData @@ -177,14 +180,14 @@ public void serialize(TestData testData, JsonGenerator jsonGenerator, Serializer EventGridPublisherAsyncClient egClient = builder .credential(getKey(CLOUD_KEY)) .endpoint(getEndpoint(CLOUD_ENDPOINT)) - .serializer(customSerializer) .buildAsyncClient(); List events = new ArrayList<>(); for (int i = 0; i < 5; i++) { - events.add(new CloudEvent("/microsoft/testEvent", "Microsoft.MockPublisher.TestEvent") + events.add(new CloudEvent("/microsoft/testEvent", "Microsoft.MockPublisher.TestEvent", + new TestData().setName("Hello " + i)) .setSubject("Test " + i) - .setData(new TestData().setName("Hello " + i))); + ); } StepVerifier.create(egClient.sendCloudEventsWithResponse(events)) @@ -230,7 +233,7 @@ public void publishEventGridEventsSync() { "1.0") .setEventTime(OffsetDateTime.now())); - Response response = egClient.sendEventsWithResponse(events, Context.NONE); + Response response = egClient.sendEventGridEventsWithResponse(events, Context.NONE); assertNotNull(response); assertEquals(response.getStatusCode(), 200); @@ -244,14 +247,14 @@ public void publishCloudEventsSync() { .buildClient(); List events = new ArrayList<>(); - events.add(new CloudEvent("/microsoft/testEvent", "Microsoft.MockPublisher.TestEvent") - .setId(UUID.randomUUID().toString()) - .setSubject("Test") - .setData(new HashMap() {{ + events.add(new CloudEvent("/microsoft/testEvent", "Microsoft.MockPublisher.TestEvent", + new HashMap() {{ put("Field1", "Value1"); put("Field2", "Value2"); put("Field3", "Value3"); }}) + .setId(UUID.randomUUID().toString()) + .setSubject("Test") .setTime(OffsetDateTime.now())); Response response = egClient.sendCloudEventsWithResponse(events, Context.NONE); diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/EventGridPublisherImplTests.java b/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/EventGridPublisherImplTests.java index dbfa528760ec0..61a4c9e9431e3 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/EventGridPublisherImplTests.java +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/test/java/com/azure/messaging/eventgrid/EventGridPublisherImplTests.java @@ -31,19 +31,19 @@ public class EventGridPublisherImplTests extends TestBase { private EventGridPublisherClientImplBuilder clientBuilder; // Event Grid endpoint for a topic accepting EventGrid schema events - private static final String EVENTGRID_ENDPOINT = "AZURE_EVENTGRID_EVENTGRID_ENDPOINT"; + private static final String EVENTGRID_ENDPOINT = "AZURE_EVENTGRID_EVENT_ENDPOINT"; // Event Grid endpoint for a topic accepting CloudEvents schema events - private static final String CLOUD_ENDPOINT = "AZURE_EVENTGRID_CLOUD_ENDPOINT"; + private static final String CLOUD_ENDPOINT = "AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"; // Event Grid endpoint for a topic accepting custom schema events private static final String CUSTOM_ENDPOINT = "AZURE_EVENTGRID_CUSTOM_ENDPOINT"; // Event Grid access key for a topic accepting EventGrid schema events - private static final String EVENTGRID_KEY = "AZURE_EVENTGRID_EVENTGRID_KEY"; + private static final String EVENTGRID_KEY = "AZURE_EVENTGRID_EVENT_KEY"; // Event Grid access key for a topic accepting CloudEvents schema events - private static final String CLOUD_KEY = "AZURE_EVENTGRID_CLOUD_KEY"; + private static final String CLOUD_KEY = "AZURE_EVENTGRID_CLOUDEVENT_KEY"; // Event Grid access key for a topic accepting custom schema events private static final String CUSTOM_KEY = "AZURE_EVENTGRID_CUSTOM_KEY"; diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/test/resources/customization/AppConfigurationKeyValueDeleted.json b/sdk/eventgrid/azure-messaging-eventgrid/src/test/resources/customization/AppConfigurationKeyValueDeleted.json index b4dce3c25c423..2341352354f5d 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/test/resources/customization/AppConfigurationKeyValueDeleted.json +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/test/resources/customization/AppConfigurationKeyValueDeleted.json @@ -6,7 +6,7 @@ "eventType": "Microsoft.AppConfiguration.KeyValueDeleted", "eventTime": "2018-01-02T19:17:44.4383997Z", "data": { - "key":"key1", + "key":"key1", "label":"label1", "etag":"etag1" }, diff --git a/sdk/eventgrid/azure-messaging-eventgrid/src/test/resources/customization/EventHubCaptureFileCreatedEvent.json b/sdk/eventgrid/azure-messaging-eventgrid/src/test/resources/customization/EventHubCaptureFileCreatedEvent.json index 52b58e9c41f66..80c992969c440 100644 --- a/sdk/eventgrid/azure-messaging-eventgrid/src/test/resources/customization/EventHubCaptureFileCreatedEvent.json +++ b/sdk/eventgrid/azure-messaging-eventgrid/src/test/resources/customization/EventHubCaptureFileCreatedEvent.json @@ -2,7 +2,7 @@ { "topic": "/subscriptions/guid/resourcegroups/rgDataMigrationSample/providers/Microsoft.EventHub/namespaces/tfdatamigratens", "subject": "eventhubs/hubdatamigration", - "eventType": "microsoft.EventHUB.CaptureFileCreated", + "eventType": "Microsoft.EventHub.CaptureFileCreated", "eventTime": "2017-08-31T19:12:46.0498024Z", "id": "14e87d03-6fbf-4bb2-9a21-92bd1281f247", "data": {