Repository navigation
Expand file tree
/
Copy pathPageToken.java
More file actions
68 lines (61 loc) · 2.33 KB
/
Copy pathPageToken.java
File metadata and controls
68 lines (61 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package io.a2a.util;
import java.time.Instant;
import io.a2a.spec.InvalidParamsError;
import org.jspecify.annotations.Nullable;
/**
* Represents a pagination token for keyset-based pagination.
* <p>
* PageTokens use the format {@code "timestamp_millis:id"} where:
* <ul>
* <li>{@code timestamp_millis} - Unix timestamp in milliseconds (numeric)</li>
* <li>{@code id} - The entity identifier (String)</li>
* </ul>
* This format enables efficient keyset pagination by allowing queries to resume
* at a specific point in a timestamp-sorted, ID-secondary-sorted result set.
*
* @param timestamp The timestamp component of the page token
* @param id The identifier component of the page token
*/
public record PageToken(Instant timestamp, String id) {
/**
* Parses a pageToken string into a PageToken record.
* <p>
* Expected format: {@code "timestamp_millis:id"}
*
* @param tokenStr The pageToken string to parse, may be null or empty
* @return A PageToken instance, or null if tokenStr is null or empty
* @throws InvalidParamsError if the token format is invalid or timestamp is not numeric
*/
public static @Nullable PageToken fromString(@Nullable String tokenStr) {
if (tokenStr == null || tokenStr.isEmpty()) {
return null;
}
String[] tokenParts = tokenStr.split(":", 2);
if (tokenParts.length != 2) {
throw new InvalidParamsError(null,
"Invalid pageToken format: expected 'timestamp:id'", null);
}
try {
long timestampMillis = Long.parseLong(tokenParts[0]);
String id = tokenParts[1];
if (id.isEmpty()) {
throw new InvalidParamsError(null, "Invalid pageToken format: id part cannot be empty", null);
}
return new PageToken(Instant.ofEpochMilli(timestampMillis), id);
} catch (NumberFormatException e) {
throw new InvalidParamsError(null,
"Invalid pageToken format: timestamp must be numeric milliseconds", null);
}
}
/**
* Converts this PageToken to its string representation.
* <p>
* Format: {@code "timestamp_millis:id"}
*
* @return The pageToken string
*/
@Override
public String toString() {
return timestamp.toEpochMilli() + ":" + id;
}
}