Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Added
* Contact metadata request/response models and `metadata_pair` filtering.
* `contact.updated` and `contact.deleted` webhook trigger constants with iCloud and Yahoo compatibility documentation.
* Added Events batch endpoint (Google and Microsoft): `Events.batch()` runs multiple event create, update and delete operations in one `POST /v3/grants/{grant_id}/events/batch` request. A 207 Multi-Status response is returned, not thrown; check each result's `status` and `error`.

### Fixed
* Building from source no longer fails when JDK 8 is not installed locally: Gradle now downloads the JDK 8 toolchain required by the build (foojay toolchain resolver). This also fixes CodeQL autobuild on GitHub's current `ubuntu-latest` runners.
Expand Down
3 changes: 3 additions & 0 deletions examples/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ NYLAS_API_URI=https://api.us.nylas.com
# You can get this from your Nylas Dashboard after connecting an account
NYLAS_GRANT_ID=your_grant_id_here

# An existing event ID to update (batch events example)
NYLAS_EVENT_ID=your_event_id_here

# Test email
NYLAS_TEST_EMAIL=your@email.com

Expand Down
20 changes: 20 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ The `EventsExample` demonstrates how to use the Nylas Java/Kotlin SDK to interac
- Filter events by date range
- Show event details

### Batch Events Example

The `BatchEventsExample` demonstrates the Events batch endpoint (Google and Microsoft only):

- Create, update and delete events in one request
- Loop over per-operation results (a 207 response is returned, not thrown)
- Retry throttled items (`429`/`503`) after `retry_after`, and never retry items with `provider_event_created: true`

Requires `NYLAS_API_KEY`, `NYLAS_GRANT_ID` and `NYLAS_EVENT_ID` (an existing event to update). `NYLAS_CALENDAR_ID` is optional and defaults to `primary`.

### Notetaker Example

The `NotetakerExample` demonstrates how to use the Nylas Java/Kotlin SDK to interact with the Notetakers API:
Expand Down Expand Up @@ -82,6 +92,9 @@ NYLAS_API_KEY=your_api_key_here
# Your grant ID (required for message examples)
NYLAS_GRANT_ID=your_grant_id_here

# An existing event ID to update (batch events example)
NYLAS_EVENT_ID=your_event_id_here

# Test email address (required for large attachments example)
NYLAS_TEST_EMAIL=test@example.com

Expand Down Expand Up @@ -112,6 +125,11 @@ Run Java Events example:
./gradlew :examples:run -PmainClass=com.nylas.examples.EventsExample
```

Run Java Batch Events example:
```bash
./gradlew :examples:run -PmainClass=com.nylas.examples.BatchEventsExample
```

Run Java Notetaker example:
```bash
./gradlew :examples:run -PmainClass=com.nylas.examples.NotetakerExample
Expand Down Expand Up @@ -170,6 +188,7 @@ make kotlin-way
- `MessagesExample.java` (Java - demonstrates new message features)
- `KotlinMessagesExample.kt` (Kotlin - demonstrates new message features)
- `EventsExample.java` (Java - demonstrates events)
- `BatchEventsExample.java` (Java - demonstrates the Events batch endpoint)
- `FoldersExample.java` (Java - demonstrates folders and single_level parameter)
- `LargeAttachmentsExample.java` (Java - demonstrates large file attachments)
- `CustomTrackingDomainExample.java` (Java - demonstrates custom link and open tracking hostnames)
Expand All @@ -191,6 +210,7 @@ examples/
│ └── com/nylas/examples/
│ ├── MessagesExample.java # NEW: Message features demo
│ ├── EventsExample.java # Events API demo
│ ├── BatchEventsExample.java # Events batch endpoint demo
│ ├── FoldersExample.java # NEW: Folders API demo with single_level parameter
│ ├── LargeAttachmentsExample.java # NEW: Large file attachments demo
│ └── NotetakerExample.java # Notetaker API demo
Expand Down
128 changes: 128 additions & 0 deletions examples/src/main/java/com/nylas/examples/BatchEventsExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package com.nylas.examples;

import com.nylas.NylasClient;
import com.nylas.models.BatchEventOperation;
import com.nylas.models.BatchEventResult;
import com.nylas.models.BatchEventsQueryParams;
import com.nylas.models.BatchEventsRequest;
import com.nylas.models.BatchEventsResponse;
import com.nylas.models.CreateEventRequest;
import com.nylas.models.NylasApiError;
import com.nylas.models.UpdateEventRequest;
import okhttp3.OkHttpClient;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Runs several event operations in one request with the Events batch endpoint (Google and Microsoft only).
*
* Reads configuration from environment variables, then from examples/.env or .env.
* Required: NYLAS_API_KEY, NYLAS_GRANT_ID, NYLAS_EVENT_ID (an existing event to update).
* Optional: NYLAS_CALENDAR_ID (defaults to "primary"), NYLAS_API_URI.
*/
public class BatchEventsExample {
private static final int MAX_ATTEMPTS = 3;
private static final double DEFAULT_RETRY_SECONDS = 1.0;

public static void main(String[] args) throws Exception {
Map<String, String> config = loadConfig();
NylasClient nylas = new NylasClient(
require(config, "NYLAS_API_KEY"),
new OkHttpClient.Builder(),
config.getOrDefault("NYLAS_API_URI", "https://api.us.nylas.com")
);
String grantId = require(config, "NYLAS_GRANT_ID");
String eventId = require(config, "NYLAS_EVENT_ID");
BatchEventsQueryParams queryParams =
new BatchEventsQueryParams.Builder(config.getOrDefault("NYLAS_CALENDAR_ID", "primary")).build();

long start = System.currentTimeMillis() / 1000L + 60 * 60 * 24;
List<BatchEventOperation> operations = Arrays.asList(
BatchEventOperation.create(new CreateEventRequest.Builder(
new CreateEventRequest.When.Timespan.Builder((int) start, (int) start + 1800).build()
).title("Batch standup").build()),
BatchEventOperation.update(eventId, new UpdateEventRequest.Builder().title("Renamed by batch").build()),
BatchEventOperation.delete("event-id-that-does-not-exist")
);

try {
for (int attempt = 1; attempt <= MAX_ATTEMPTS && !operations.isEmpty(); attempt++) {
// A 207 (some or all operations failed) is returned, not thrown.
// Any other non-2xx status for the whole call (e.g. 400 for an invalid batch) throws NylasApiError.
BatchEventsResponse response = nylas.events().batch(grantId, new BatchEventsRequest(operations), queryParams);
System.out.println("Attempt " + attempt + " (request_id " + response.getRequestId() + "):");

List<BatchEventOperation> retry = new ArrayList<>();
double waitSeconds = 0;

// data.get(i) is the result of operations.get(i).
for (int i = 0; i < response.getData().size(); i++) {
BatchEventResult result = response.getData().get(i);
if (result.getError() == null) {
System.out.println(" " + i + ": OK " + result.getStatus()
+ (result.getData() != null ? " event " + result.getData().getId() : ""));
continue;
}
System.out.println(" " + i + ": FAILED " + result.getStatus() + " " + result.getError().getMessage());

// Never retry an item the provider already created: retrying would create a duplicate event.
if (Boolean.TRUE.equals(result.getProviderEventCreated())) {
System.out.println(" not retrying: the provider already created this event");
continue;
}
if (result.getStatus() == 429 || result.getStatus() == 503) {
retry.add(operations.get(i));
double retryAfter = result.getRetryAfter() != null ? result.getRetryAfter() : DEFAULT_RETRY_SECONDS;
waitSeconds = Math.max(waitSeconds, retryAfter);
}
}

if (!retry.isEmpty() && attempt < MAX_ATTEMPTS) {
System.out.println("Retrying " + retry.size() + " throttled operation(s) after " + waitSeconds + "s");
Thread.sleep((long) (waitSeconds * 1000));
}
operations = retry;
}
} catch (NylasApiError e) {
System.out.println("Batch request failed (HTTP " + e.getStatusCode() + "): " + e.getMessage()
+ " request_id=" + e.getRequestId());
}
}

private static Map<String, String> loadConfig() {
Map<String, String> config = new HashMap<>(System.getenv());
for (String path : Arrays.asList("examples/.env", ".env")) {
File envFile = new File(path);
if (!envFile.exists()) {
continue;
}
try {
for (String line : Files.readAllLines(envFile.toPath())) {
String[] parts = line.split("=", 2);
if (parts.length == 2 && !line.trim().startsWith("#")) {
config.putIfAbsent(parts[0].trim(), parts[1].trim());
}
}
} catch (IOException e) {
System.out.println("Warning: failed to read " + path + ": " + e.getMessage());
}
}
return config;
}

private static String require(Map<String, String> config, String key) {
String value = config.get(key);
if (value == null || value.isEmpty()) {
throw new IllegalArgumentException(
"Missing required configuration: " + key + ". Set it in examples/.env or as an environment variable.");
}
return value;
}
}
70 changes: 70 additions & 0 deletions src/main/kotlin/com/nylas/models/BatchEventOperation.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package com.nylas.models

import com.squareup.moshi.Json

/**
* Class representation of a single operation in an events batch request.
*
* Use the [create], [update] and [delete] factory methods to build an operation,
* so that each operation always carries the fields its method requires.
*/
class BatchEventOperation private constructor(
/**
* The operation to run.
*/
@Json(name = "method")
val method: BatchEventMethod,
/**
* The ID of the event to update or delete. Null for create operations.
*/
@Json(name = "event_id")
val eventId: String? = null,
/**
* The request body: a [CreateEventRequest] for create operations,
* an [UpdateEventRequest] for update operations, and null for delete operations.
* Typed as Any? so one field holds either request type; the factory methods keep it type-safe.
*/
@Json(name = "body")
val body: Any? = null,
) {
companion object {
/**
* Build a create operation.
* @param requestBody The values to create the event with
* @return The create operation
*/
@JvmStatic
fun create(requestBody: CreateEventRequest) = BatchEventOperation(BatchEventMethod.CREATE, body = requestBody)

/**
* Build an update operation.
* @param eventId The ID of the event to update
* @param requestBody The values to update the event with
* @return The update operation
*/
@JvmStatic
fun update(eventId: String, requestBody: UpdateEventRequest) = BatchEventOperation(BatchEventMethod.UPDATE, eventId, requestBody)

/**
* Build a delete operation.
* @param eventId The ID of the event to delete
* @return The delete operation
*/
@JvmStatic
fun delete(eventId: String) = BatchEventOperation(BatchEventMethod.DELETE, eventId)
}
}

/**
* Enum representation of the operations supported in an events batch request.
*/
enum class BatchEventMethod {
@Json(name = "create")
CREATE,

@Json(name = "update")
UPDATE,

@Json(name = "delete")
DELETE,
}
90 changes: 90 additions & 0 deletions src/main/kotlin/com/nylas/models/BatchEventsQueryParams.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package com.nylas.models

import com.squareup.moshi.Json

/**
* Class representation of the query parameters for an events batch request.
* These apply to every operation in the batch.
*/
data class BatchEventsQueryParams(
/**
* The ID of the calendar the operations run against.
*/
@Json(name = "calendar_id")
val calendarId: String,
/**
* Whether to send email notifications to all event participants.
* Microsoft accounts do not support notify_participants = False.
*/
@Json(name = "notify_participants")
val notifyParticipants: Boolean? = null,
/**
* The email address of the grant.
*/
@Json(name = "grant_email")
val grantEmail: String? = null,
/**
* When true, tentative events are counted as busy.
*/
@Json(name = "tentative_as_busy")
val tentativeAsBusy: Boolean? = null,
/**
* Comma-separated list of fields to return for each event.
*/
@Json(name = "select")
val select: String? = null,
) : IQueryParams {
/**
* Builder for [BatchEventsQueryParams].
* @property calendarId The ID of the calendar the operations run against.
*/
data class Builder(
private val calendarId: String,
) {
private var notifyParticipants: Boolean? = null
private var grantEmail: String? = null
private var tentativeAsBusy: Boolean? = null
private var select: String? = null

/**
* Sets whether to send email notifications to all event participants.
* Microsoft accounts do not support notify_participants = False.
* @param notifyParticipants Whether to send email notifications.
* @return The builder.
*/
fun notifyParticipants(notifyParticipants: Boolean?) = apply { this.notifyParticipants = notifyParticipants }

/**
* Sets the email address of the grant.
* @param grantEmail The email address of the grant.
* @return The builder.
*/
fun grantEmail(grantEmail: String?) = apply { this.grantEmail = grantEmail }

/**
* Sets whether tentative events are counted as busy.
* @param tentativeAsBusy Whether tentative events are counted as busy.
* @return The builder.
*/
fun tentativeAsBusy(tentativeAsBusy: Boolean?) = apply { this.tentativeAsBusy = tentativeAsBusy }

/**
* Sets the comma-separated list of fields to return for each event.
* @param select The fields to return.
* @return The builder.
*/
fun select(select: String?) = apply { this.select = select }

/**
* Builds a [BatchEventsQueryParams] instance.
* @return The [BatchEventsQueryParams] instance.
*/
fun build() = BatchEventsQueryParams(
calendarId,
notifyParticipants,
grantEmail,
tentativeAsBusy,
select,
)
}
}
14 changes: 14 additions & 0 deletions src/main/kotlin/com/nylas/models/BatchEventsRequest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.nylas.models

import com.squareup.moshi.Json

/**
* Class representation of a Nylas events batch request.
*/
data class BatchEventsRequest(
/**
* The operations to run. Results are returned in the same order.
*/
@Json(name = "operations")
val operations: List<BatchEventOperation>,
)
Loading
Loading