azure-eventgrid-java
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.
About this skill
This skill equips an AI agent with the knowledge and code snippets required to build robust event-driven applications in Java, leveraging the Azure Event Grid SDK. It enables the agent to assist developers in tasks such as publishing custom events, subscribing to events, implementing sophisticated publish-subscribe messaging patterns, and integrating various Azure services through event-based communication. The skill provides the necessary Java dependencies and client creation examples, allowing the agent to generate relevant, ready-to-use code efficiently for interacting with Azure Event Grid.
Best use case
Generating Java code to publish custom events to Azure Event Grid topics or domains. Creating Java-based event handlers or subscribers for Event Grid events. Designing and implementing publish-subscribe architectures using Azure Event Grid in Java applications. Integrating Java microservices or serverless applications (e.g., Azure Functions) with other Azure services (e.g., Storage Accounts, IoT Hub) through event-driven communication. Assisting developers in setting up event routing, filtering logic, and custom event schemas within Azure Event Grid. Providing code examples for authenticating and initializing Event Grid publisher clients in Java.
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.
The AI agent will generate accurate and functional Java code snippets or complete examples for interacting with Azure Event Grid, including dependency management, client initialization, and event publishing/consumption logic. This leads to faster development, reduced boilerplate, and correct implementation of event-driven features in Java applications integrated with Azure.
Practical example
Example input
Generate a Java code snippet using the Azure Event Grid SDK to publish a custom event named 'UserRegistered' to an Event Grid topic, including client creation and the necessary Maven dependency.
Example output
```xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventgrid</artifactId>
<version>4.27.0</version>
</dependency>
```
```java
import com.azure.messaging.eventgrid.EventGridPublisherClient;
import com.azure.messaging.eventgrid.EventGridPublisherClientBuilder;
import com.azure.messaging.eventgrid.models.CloudEvent;
import com.azure.core.credential.AzureKeyCredential;
import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.UUID;
public class UserRegisteredEventPublisher {
public static void main(String[] args) {
// Replace with your Event Grid Topic Endpoint and Key
String topicEndpoint = System.getenv("EVENT_GRID_TOPIC_ENDPOINT");
String topicKey = System.getenv("EVENT_GRID_TOPIC_KEY");
if (topicEndpoint == null || topicKey == null) {
System.err.println("Please set EVENT_GRID_TOPIC_ENDPOINT and EVENT_GRID_TOPIC_KEY environment variables.");
return;
}
EventGridPublisherClient<CloudEvent> publisherClient = new EventGridPublisherClientBuilder()
.endpoint(topicEndpoint)
.credential(new AzureKeyCredential(topicKey))
.buildCloudEventPublisherClient();
// Create a custom CloudEvent for user registration
CloudEvent userRegisteredEvent = new CloudEvent()
.setId(UUID.randomUUID().toString())
.setSource("https://mycompany.com/authservice") // Origin of the event
.setType("UserRegistered")
.setTime(OffsetDateTime.now())
.setData("{\"userId\": \"user-123\", \"email\": \"john.doe@example.com\", \"timestamp\": \"" + OffsetDateTime.now().toString() + "\"}") // Event data as JSON string
.setSpecVersion("1.0");
// Publish the event
try {
publisherClient.sendEvents(Collections.singletonList(userRegisteredEvent));
System.out.println("Custom event 'UserRegistered' published successfully.");
} catch (Exception e) {
System.err.println("Failed to publish event: " + e.getMessage());
e.printStackTrace();
}
}
}
```When to use this skill
- When an AI agent needs to provide Java code solutions for event-driven architectures using Azure.
- When developing or integrating Java applications with Azure Event Grid for real-time event processing.
- When implementing reactive patterns, microservices communication, or serverless event handling in Java.
- When an agent is asked to generate examples or templates for event publishing and consumption in Java for Azure services.
When not to use this skill
- When the target application is not built in Java or does not require Java code generation.
- When the eventing solution is not Azure Event Grid (e.g., Kafka, RabbitMQ, AWS SNS/SQS, Google Pub/Sub).
- When the task does not involve event-driven programming or Azure cloud services.
- When the AI agent's role is strictly informational and does not involve generating or assisting with code development.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/azure-eventgrid-java/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How azure-eventgrid-java Compares
| Feature / Agent | azure-eventgrid-java | Standard Approach |
|---|---|---|
| Platform Support | Claude, ChatGPT, Gemini | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | easy | N/A |
Frequently Asked Questions
What does this skill do?
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.
Which AI agents support this skill?
This skill is designed for Claude, ChatGPT, Gemini.
How difficult is it to install?
The installation complexity is rated as easy. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# 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.identity.DefaultAzureCredentialBuilder;
EventGridPublisherClient<EventGridEvent> client = new EventGridPublisherClientBuilder()
.endpoint("<topic-endpoint>")
.credential(new DefaultAzureCredentialBuilder().build())
.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
EVENT_GRID_ACCESS_KEY=<your-access-key>
```
## 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"
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.Related Skills
azure-storage-queue-ts
Azure Queue Storage JavaScript/TypeScript SDK (@azure/storage-queue) for message queue operations. Use for sending, receiving, peeking, and deleting messages in queues.
azure-storage-queue-py
Azure Queue Storage SDK for Python. Use for reliable message queuing, task distribution, and asynchronous processing.
azure-servicebus-dotnet
Azure Service Bus SDK for .NET. Enterprise messaging with queues, topics, subscriptions, and sessions.
azure-monitor-ingestion-java
Azure Monitor Ingestion SDK for Java. Send custom logs to Azure Monitor via Data Collection Rules (DCR) and Data Collection Endpoints (DCE).
azure-identity-py
Azure Identity SDK for Python authentication. Use for DefaultAzureCredential, managed identity, service principals, and token caching.
azure-eventgrid-py
Azure Event Grid SDK for Python. Use for publishing events, handling CloudEvents, and event-driven architectures.
azure-eventgrid-dotnet
Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents.
n8n-code-javascript
Write JavaScript code in n8n Code nodes. Use when writing JavaScript in n8n, using $input/$json/$node syntax, making HTTP requests with $helpers, working with dates using DateTime, troubleshooting Code node errors, or choosing between Code node modes.
microsoft-azure-webjobs-extensions-authentication-events-dotnet
Microsoft Entra Authentication Events SDK for .NET. Azure Functions triggers for custom authentication extensions.
javascript-typescript-typescript-scaffold
You are a TypeScript project architecture expert specializing in scaffolding production-ready Node.js and frontend applications. Generate complete project structures with modern tooling (pnpm, Vite, N
javascript-pro
Master modern JavaScript with ES6+, async patterns, and Node.js APIs. Handles promises, event loops, and browser/Node compatibility.
javascript-mastery
33+ essential JavaScript concepts every developer should know, inspired by [33-js-concepts](https://github.com/leonardomso/33-js-concepts).