# SkillPatch skill: azure-eventgrid-java

This skill provides guidance for building event-driven applications using the Azure Event Grid SDK for Java. It covers client creation (sync/async, API key and DefaultAzureCredential), publishing EventGrid events and CloudEvents, and working with multiple event types including custom schemas. Agents can follow the detailed code patterns to integrate Azure Event Grid pub/sub into Java applications.

You (the agent) were given this URL and asked to use this skill. This is a **public** skill — no SkillPatch account, API key, or prior setup is required. Two ways to use it:

**1. Use it right now** — the skill's complete file tree (SKILL.md + all reference files) is inlined below; read `SKILL.md` first, then follow it, consulting the other files as it directs.

**2. Install the exact package onto disk** (recommended if you can run a shell — this reproduces the skill byte-for-byte, including any binary assets that can't be inlined):

```bash
mkdir -p .claude/skills/azure-eventgrid-java
curl -sSL https://skillpatch.dev/install_skill/azure-eventgrid-java | tar -xz -C .claude/skills/
```

(`.claude/skills/` is Claude Code's convention; use whatever directory your agent loads skills from.)


---

## Skill files (2)

- `SKILL.md`
- `references/examples.md`


### `SKILL.md`

````markdown
---
name: azure-eventgrid-java
description: Build event-driven applications with Azure Event Grid SDK for Java. Use when publishing events, implementing pub/sub patterns, or integrating with Azure services via events.
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
  package: com.azure:azure-messaging-eventgrid
---

# Azure Event Grid SDK for Java

Build event-driven applications using the Azure Event Grid SDK for Java.

## Installation

```xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-messaging-eventgrid</artifactId>
    <version>4.27.0</version>
</dependency>
```

## Client Creation

### EventGridPublisherClient

```java
import com.azure.messaging.eventgrid.EventGridPublisherClient;
import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder;
import com.azure.core.credential.AzureKeyCredential;

// With API Key
EventGridPublisherClient<EventGridEvent> client = new EventGridPublisherClientBuilder()
    .endpoint("<topic-endpoint>")
    .credential(new AzureKeyCredential("<access-key>"))
    .buildEventGridEventPublisherClient();

// For CloudEvents
EventGridPublisherClient<CloudEvent> cloudClient = new EventGridPublisherClientBuilder()
    .endpoint("<topic-endpoint>")
    .credential(new AzureKeyCredential("<access-key>"))
    .buildCloudEventPublisherClient();
```

### With DefaultAzureCredential

```java
import com.azure.core.credential.TokenCredential;
import com.azure.identity.AzureIdentityEnvVars;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.identity.ManagedIdentityCredentialBuilder;

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
TokenCredential credential = new DefaultAzureCredentialBuilder()
    .requireEnvVars(AzureIdentityEnvVars.AZURE_TOKEN_CREDENTIALS)
    .build();
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/java/api/overview/azure/identity-readme?view=azure-java-stable#credential-classes
// TokenCredential credential = new ManagedIdentityCredentialBuilder().build();

EventGridPublisherClient<EventGridEvent> client = new EventGridPublisherClientBuilder()
    .endpoint("<topic-endpoint>")
    .credential(credential)
    .buildEventGridEventPublisherClient();
```

### Async Client

```java
import com.azure.messaging.eventgrid.EventGridPublisherAsyncClient;

EventGridPublisherAsyncClient<EventGridEvent> asyncClient = new EventGridPublisherClientBuilder()
    .endpoint("<topic-endpoint>")
    .credential(new AzureKeyCredential("<access-key>"))
    .buildEventGridEventPublisherAsyncClient();
```

## Event Types

| Type | Description |
|------|-------------|
| `EventGridEvent` | Azure Event Grid native schema |
| `CloudEvent` | CNCF CloudEvents 1.0 specification |
| `BinaryData` | Custom schema events |

## Core Patterns

### Publish EventGridEvent

```java
import com.azure.messaging.eventgrid.EventGridEvent;
import com.azure.core.util.BinaryData;

EventGridEvent event = new EventGridEvent(
    "resource/path",           // subject
    "MyApp.Events.OrderCreated", // eventType
    BinaryData.fromObject(new OrderData("order-123", 99.99)), // data
    "1.0"                      // dataVersion
);

client.sendEvent(event);
```

### Publish Multiple Events

```java
List<EventGridEvent> events = Arrays.asList(
    new EventGridEvent("orders/1", "Order.Created", 
        BinaryData.fromObject(order1), "1.0"),
    new EventGridEvent("orders/2", "Order.Created", 
        BinaryData.fromObject(order2), "1.0")
);

client.sendEvents(events);
```

### Publish CloudEvent

```java
import com.azure.core.models.CloudEvent;
import com.azure.core.models.CloudEventDataFormat;

CloudEvent cloudEvent = new CloudEvent(
    "/myapp/orders",           // source
    "order.created",           // type
    BinaryData.fromObject(orderData), // data
    CloudEventDataFormat.JSON  // dataFormat
);
cloudEvent.setSubject("orders/12345");
cloudEvent.setId(UUID.randomUUID().toString());

cloudClient.sendEvent(cloudEvent);
```

### Publish CloudEvents Batch

```java
List<CloudEvent> cloudEvents = Arrays.asList(
    new CloudEvent("/app", "event.type1", BinaryData.fromString("data1"), CloudEventDataFormat.JSON),
    new CloudEvent("/app", "event.type2", BinaryData.fromString("data2"), CloudEventDataFormat.JSON)
);

cloudClient.sendEvents(cloudEvents);
```

### Async Publishing

```java
asyncClient.sendEvent(event)
    .subscribe(
        unused -> System.out.println("Event sent successfully"),
        error -> System.err.println("Error: " + error.getMessage())
    );

// With multiple events
asyncClient.sendEvents(events)
    .doOnSuccess(unused -> System.out.println("All events sent"))
    .doOnError(error -> System.err.println("Failed: " + error))
    .block(); // Block if needed
```

### Custom Event Data Class

```java
public class OrderData {
    private String orderId;
    private double amount;
    private String customerId;
    
    public OrderData(String orderId, double amount) {
        this.orderId = orderId;
        this.amount = amount;
    }
    
    // Getters and setters
}

// Usage
OrderData order = new OrderData("ORD-123", 150.00);
EventGridEvent event = new EventGridEvent(
    "orders/" + order.getOrderId(),
    "MyApp.Order.Created",
    BinaryData.fromObject(order),
    "1.0"
);
```

## Receiving Events

### Parse EventGridEvent

```java
import com.azure.messaging.eventgrid.EventGridEvent;

// From JSON string (e.g., webhook payload)
String jsonPayload = "[{\"id\": \"...\", ...}]";
List<EventGridEvent> events = EventGridEvent.fromString(jsonPayload);

for (EventGridEvent event : events) {
    System.out.println("Event Type: " + event.getEventType());
    System.out.println("Subject: " + event.getSubject());
    System.out.println("Event Time: " + event.getEventTime());
    
    // Get data
    BinaryData data = event.getData();
    OrderData orderData = data.toObject(OrderData.class);
}
```

### Parse CloudEvent

```java
import com.azure.core.models.CloudEvent;

String cloudEventJson = "[{\"specversion\": \"1.0\", ...}]";
List<CloudEvent> cloudEvents = CloudEvent.fromString(cloudEventJson);

for (CloudEvent event : cloudEvents) {
    System.out.println("Type: " + event.getType());
    System.out.println("Source: " + event.getSource());
    System.out.println("ID: " + event.getId());
    
    MyEventData data = event.getData().toObject(MyEventData.class);
}
```

### Handle System Events

```java
import com.azure.messaging.eventgrid.systemevents.*;

for (EventGridEvent event : events) {
    if (event.getEventType().equals("Microsoft.Storage.BlobCreated")) {
        StorageBlobCreatedEventData blobData = 
            event.getData().toObject(StorageBlobCreatedEventData.class);
        System.out.println("Blob URL: " + blobData.getUrl());
    }
}
```

## Event Grid Namespaces (MQTT/Pull)

### Receive from Namespace Topic

```java
import com.azure.messaging.eventgrid.namespaces.EventGridReceiverClient;
import com.azure.messaging.eventgrid.namespaces.EventGridReceiverClientBuilder;
import com.azure.messaging.eventgrid.namespaces.models.*;

EventGridReceiverClient receiverClient = new EventGridReceiverClientBuilder()
    .endpoint("<namespace-endpoint>")
    .credential(new AzureKeyCredential("<key>"))
    .topicName("my-topic")
    .subscriptionName("my-subscription")
    .buildClient();

// Receive events
ReceiveResult result = receiverClient.receive(10, Duration.ofSeconds(30));

for (ReceiveDetails detail : result.getValue()) {
    CloudEvent event = detail.getEvent();
    System.out.println("Event: " + event.getType());
    
    // Acknowledge the event
    receiverClient.acknowledge(Arrays.asList(detail.getBrokerProperties().getLockToken()));
}
```

### Reject or Release Events

```java
// Reject (don't retry)
receiverClient.reject(Arrays.asList(lockToken));

// Release (retry later)
receiverClient.release(Arrays.asList(lockToken));

// Release with delay
receiverClient.release(Arrays.asList(lockToken), 
    new ReleaseOptions().setDelay(ReleaseDelay.BY_60_SECONDS));
```

## Error Handling

```java
import com.azure.core.exception.HttpResponseException;

try {
    client.sendEvent(event);
} catch (HttpResponseException e) {
    System.out.println("Status: " + e.getResponse().getStatusCode());
    System.out.println("Error: " + e.getMessage());
}
```

## Environment Variables

```bash
EVENT_GRID_TOPIC_ENDPOINT=https://<topic-name>.<region>.eventgrid.azure.net/api/events  # Required for all auth methods
EVENT_GRID_ACCESS_KEY=<your-access-key>  # Only required for AzureKeyCredential auth
AZURE_TOKEN_CREDENTIALS=prod  # Required only if DefaultAzureCredential is used in production
```

## Best Practices

1. **Batch Events**: Send multiple events in one call when possible
2. **Idempotency**: Include unique event IDs for deduplication
3. **Schema Validation**: Use strongly-typed event data classes
4. **Retry Logic**: Built-in, but consider dead-letter for failures
5. **Event Size**: Keep events under 1MB (64KB for basic tier)

## Trigger Phrases

- "Event Grid Java"
- "publish events Azure"
- "CloudEvent SDK"
- "event-driven messaging"
- "pub/sub Azure"
- "webhook events"

````


### `references/examples.md`

````markdown
# Azure Event Grid SDK for Java - Examples

Comprehensive code examples for the Azure Event Grid SDK for Java.

## Table of Contents
- [Maven Dependency](#maven-dependency)
- [Client Creation](#client-creation)
- [Publishing CloudEvents](#publishing-cloudevents)
- [Publishing EventGridEvents](#publishing-eventgridevents)
- [Publishing Custom Events](#publishing-custom-events)
- [Async Client Patterns](#async-client-patterns)
- [Batch Publishing](#batch-publishing)
- [Error Handling](#error-handling)

## Maven Dependency

```xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-messaging-eventgrid</artifactId>
    <version>4.32.0-beta.1</version>
</dependency>

<!-- For DefaultAzureCredential authentication -->
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-identity</artifactId>
    <version>1.18.2</version>
</dependency>
```

## Client Creation

### Sync Client with DefaultAzureCredential

```java
import com.azure.core.models.CloudEvent;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.messaging.eventgrid.EventGridPublisherClient;
import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder;

EventGridPublisherClient<CloudEvent> cloudEventClient = new EventGridPublisherClientBuilder()
    .endpoint("<endpoint of your event grid topic/domain that accepts CloudEvent schema>")
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildCloudEventPublisherClient();
```

### Async Client with DefaultAzureCredential

```java
import com.azure.messaging.eventgrid.EventGridPublisherAsyncClient;

EventGridPublisherAsyncClient<CloudEvent> cloudEventAsyncClient = new EventGridPublisherClientBuilder()
    .endpoint("<endpoint of your event grid topic/domain that accepts CloudEvent schema>")
    .credential(new DefaultAzureCredentialBuilder().build())
    .buildCloudEventPublisherAsyncClient();
```

### Client with AzureKeyCredential

```java
import com.azure.core.credential.AzureKeyCredential;

EventGridPublisherClient<CloudEvent> client = new EventGridPublisherClientBuilder()
    .endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"))
    .credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")))
    .buildCloudEventPublisherClient();
```

## Publishing CloudEvents

```java
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.models.CloudEvent;
import com.azure.core.models.CloudEventDataFormat;
import com.azure.core.util.BinaryData;
import com.azure.messaging.eventgrid.EventGridPublisherClient;
import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class PublishCloudEventsToTopic {
    public static void main(String[] args) {
        EventGridPublisherClient<CloudEvent> publisherClient = new EventGridPublisherClientBuilder()
            .endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"))
            .credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")))
            .buildCloudEventPublisherClient();

        // CloudEvent with String data
        String str = "FirstName: John1, LastName:James";
        CloudEvent cloudEventStr = new CloudEvent("https://com.example.myapp", "User.Created.Text",
            BinaryData.fromObject(str), CloudEventDataFormat.JSON, "text/plain");

        // CloudEvent with Object data
        User newUser = new User("John2", "James");
        CloudEvent cloudEventModel = new CloudEvent("https://com.example.myapp", "User.Created.Object",
            BinaryData.fromObject(newUser), CloudEventDataFormat.JSON, "application/json");
        
        // CloudEvent with bytes data
        byte[] byteSample = "FirstName: John3, LastName: James".getBytes(StandardCharsets.UTF_8);
        CloudEvent cloudEventBytes = new CloudEvent("https://com.example.myapp", "User.Created.Binary",
            BinaryData.fromBytes(byteSample), CloudEventDataFormat.BYTES, "application/octet-stream");

        // CloudEvent with extension attributes
        CloudEvent cloudEventWithExtension = cloudEventBytes.addExtensionAttribute("extension", "value");

        // Send batch
        List<CloudEvent> events = new ArrayList<>();
        events.add(cloudEventStr);
        events.add(cloudEventModel);
        events.add(cloudEventBytes);
        events.add(cloudEventWithExtension);
        
        publisherClient.sendEvents(events);
    }
}
```

## Publishing EventGridEvents

```java
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.BinaryData;
import com.azure.messaging.eventgrid.EventGridEvent;
import com.azure.messaging.eventgrid.EventGridPublisherClient;
import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder;

import java.util.ArrayList;
import java.util.List;

public class PublishEventGridEventsToTopic {
    public static void main(String[] args) {
        EventGridPublisherClient<EventGridEvent> publisherClient = new EventGridPublisherClientBuilder()
            .endpoint(System.getenv("AZURE_EVENTGRID_EVENT_ENDPOINT"))
            .credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_EVENT_KEY")))
            .buildEventGridEventPublisherClient();

        // EventGridEvent with String data
        String str = "FirstName: John1, LastName: James";
        EventGridEvent eventJson = new EventGridEvent(
            "com/example/MyApp",           // subject
            "User.Created.Text",           // eventType
            BinaryData.fromObject(str),    // data
            "0.1"                          // dataVersion
        );
        
        // EventGridEvent with Object data
        User newUser = new User("John2", "James");
        EventGridEvent eventModelClass = new EventGridEvent(
            "com/example/MyApp",
            "User.Created.Object",
            BinaryData.fromObject(newUser),
            "0.1"
        );

        List<EventGridEvent> events = new ArrayList<>();
        events.add(eventJson);
        events.add(eventModelClass);

        publisherClient.sendEvents(events);
    }
}
```

## Publishing Custom Events

```java
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.BinaryData;
import com.azure.messaging.eventgrid.EventGridPublisherClient;
import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder;

import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

public class PublishCustomEvents {
    public static void main(String[] args) {
        // Create custom event publisher client
        EventGridPublisherClient<BinaryData> customEventClient = new EventGridPublisherClientBuilder()
            .endpoint("<endpoint of your event grid topic/domain that accepts custom event schema>")
            .credential(new AzureKeyCredential("<key for the endpoint>"))
            .buildCustomEventPublisherClient();

        // Build custom event as a map
        List<BinaryData> events = new ArrayList<>();
        events.add(BinaryData.fromObject(new HashMap<String, String>() {
            {
                put("id", UUID.randomUUID().toString());
                put("time", OffsetDateTime.now().toString());
                put("subject", "Test");
                put("foo", "bar");
                put("type", "Microsoft.MockPublisher.TestEvent");
                put("data", "example data");
                put("dataVersion", "0.1");
            }
        }));
        
        customEventClient.sendEvents(events);
    }
}
```

## Async Client Patterns

### Async CloudEvent Publishing

```java
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.models.CloudEvent;
import com.azure.core.models.CloudEventDataFormat;
import com.azure.core.util.BinaryData;
import com.azure.messaging.eventgrid.EventGridPublisherAsyncClient;
import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class PublishCloudEventsAsynchronously {
    public static void main(String[] args) throws Exception {
        EventGridPublisherAsyncClient<CloudEvent> publisherClient = new EventGridPublisherClientBuilder()
            .endpoint(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_ENDPOINT"))
            .credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_CLOUDEVENT_KEY")))
            .buildCloudEventPublisherAsyncClient();

        // Create CloudEvents
        User newUser = new User("John2", "James");
        CloudEvent cloudEventModel = new CloudEvent("https://com.example.myapp", "User.Created.Object",
            BinaryData.fromObject(newUser), CloudEventDataFormat.JSON, "application/json");

        byte[] byteSample = "FirstName: John3, LastName: James".getBytes(StandardCharsets.UTF_8);
        CloudEvent cloudEventBytes = new CloudEvent("https://com.example.myapp", "User.Created.Binary",
            BinaryData.fromBytes(byteSample), CloudEventDataFormat.BYTES, "application/octet-stream");

        List<CloudEvent> events = new ArrayList<>();
        events.add(cloudEventModel);
        events.add(cloudEventBytes);

        // Non-blocking send with subscribe()
        publisherClient.sendEvents(events)
            .subscribe(
                unused -> System.out.println("Events sent successfully"),
                error -> System.err.println("Error sending events: " + error.getMessage()),
                () -> System.out.println("Send operation completed")
            );

        // Keep application alive for async operation
        Thread.sleep(5000);
    }
}
```

### Async EventGridEvent Publishing

```java
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.BinaryData;
import com.azure.messaging.eventgrid.EventGridEvent;
import com.azure.messaging.eventgrid.EventGridPublisherAsyncClient;
import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder;

import java.util.ArrayList;
import java.util.List;

public class PublishEventGridEventsAsynchronously {
    public static void main(String[] args) throws Exception {
        EventGridPublisherAsyncClient<EventGridEvent> publisherClient = new EventGridPublisherClientBuilder()
            .endpoint(System.getenv("AZURE_EVENTGRID_EVENT_ENDPOINT"))
            .credential(new AzureKeyCredential(System.getenv("AZURE_EVENTGRID_EVENT_KEY")))
            .buildEventGridEventPublisherAsyncClient();

        String str = "FirstName: John1, LastName: James";
        EventGridEvent eventJson = new EventGridEvent("com/example/MyApp", "User.Created.Text", 
            BinaryData.fromObject(str), "0.1");
        
        User newUser = new User("John2", "James");
        EventGridEvent eventModelClass = new EventGridEvent("com/example/MyApp", "User.Created.Object", 
            BinaryData.fromObject(newUser), "0.1");

        List<EventGridEvent> events = new ArrayList<>();
        events.add(eventJson);
        events.add(eventModelClass);

        // Non-blocking send
        publisherClient.sendEvents(events)
            .subscribe();

        Thread.sleep(5000);
    }
}
```

## Batch Publishing

All `sendEvents()` methods accept a `List` and publish as a batch:

```java
// CloudEvents batch
List<CloudEvent> cloudEvents = new ArrayList<>();
cloudEvents.add(event1);
cloudEvents.add(event2);
cloudEvents.add(event3);
publisherClient.sendEvents(cloudEvents);

// EventGridEvents batch
List<EventGridEvent> gridEvents = new ArrayList<>();
gridEvents.add(gridEvent1);
gridEvents.add(gridEvent2);
publisherClient.sendEvents(gridEvents);

// Custom events batch
List<BinaryData> customEvents = new ArrayList<>();
customEvents.add(BinaryData.fromObject(customEvent1));
customEvents.add(BinaryData.fromObject(customEvent2));
customEventClient.sendEvents(customEvents);
```

## Error Handling

```java
import com.azure.core.exception.HttpResponseException;
import com.azure.core.models.CloudEvent;
import com.azure.messaging.eventgrid.EventGridPublisherClient;

public class EventGridErrorHandling {
    public static void main(String[] args) {
        EventGridPublisherClient<CloudEvent> client = /* create client */;
        
        try {
            client.sendEvents(events);
        } catch (HttpResponseException e) {
            System.err.println("HTTP Status Code: " + e.getResponse().getStatusCode());
            System.err.println("Error Message: " + e.getMessage());
            
            // Handle specific status codes
            int statusCode = e.getResponse().getStatusCode();
            if (statusCode == 401 || statusCode == 403) {
                System.err.println("Authentication/Authorization error");
            } else if (statusCode == 404) {
                System.err.println("Topic/Domain not found");
            } else if (statusCode >= 500) {
                System.err.println("Server error - consider retry");
            }
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
        }
    }
}
```

### Async Error Handling

```java
publisherClient.sendEvents(events)
    .subscribe(
        unused -> System.out.println("Success"),
        error -> {
            if (error instanceof HttpResponseException) {
                HttpResponseException httpError = (HttpResponseException) error;
                System.err.println("HTTP error: " + httpError.getResponse().getStatusCode());
            } else {
                System.err.println("Error: " + error.getMessage());
            }
        },
        () -> System.out.println("Completed")
    );
```

## Helper Class

```java
public class User {
    private String firstName;
    private String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() { return firstName; }
    public void setFirstName(String firstName) { this.firstName = firstName; }
    public String getLastName() { return lastName; }
    public void setLastName(String lastName) { this.lastName = lastName; }
}
```

````
