Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
Expand All @@ -34,6 +36,7 @@
import org.a2aproject.sdk.client.http.A2AHttpClientFactory;
import org.a2aproject.sdk.client.http.A2AHttpClientFactory.ClientSelection;
import org.a2aproject.sdk.client.http.A2AHttpResponse;
import org.a2aproject.sdk.client.http.HttpEndpoint;
import org.a2aproject.sdk.client.http.HttpStreamLifecycle;
import org.a2aproject.sdk.common.A2AHeaders;
import org.a2aproject.sdk.client.transport.rest.sse.SSEEventListener;
Expand Down Expand Up @@ -180,9 +183,9 @@ public Task getTask(TaskQueryParams taskQueryParams, @Nullable ClientCallContext
org.a2aproject.sdk.grpc.GetTaskRequestOrBuilder effective = InterceptorPayloads.cast(payloadAndHeaders.getPayload(), org.a2aproject.sdk.grpc.GetTaskRequestOrBuilder.class);
StringBuilder url = new StringBuilder(Utils.buildBaseUrl(agentInterface, effective.getTenant()));
if (effective.hasHistoryLength()) {
url.append(String.format("/tasks/%s?historyLength=%d", effective.getId(), effective.getHistoryLength()));
url.append(String.format("/tasks/%s?historyLength=%d", HttpEndpoint.pathSegment("taskId", effective.getId()), effective.getHistoryLength()));
} else {
url.append(String.format("/tasks/%1s", effective.getId()));
url.append(String.format("/tasks/%1s", HttpEndpoint.pathSegment("taskId", effective.getId())));
}
A2AHttpClient.GetBuilder getBuilder = httpClient.createGet().url(url.toString());
addStandardHeaders(getBuilder, payloadAndHeaders);
Expand All @@ -208,7 +211,7 @@ public Task cancelTask(CancelTaskParams taskIdParams, @Nullable ClientCallContex
PayloadAndHeaders payloadAndHeaders = applyInterceptors(CANCEL_TASK_METHOD, builder, agentCard, context);
try {
org.a2aproject.sdk.grpc.CancelTaskRequestOrBuilder effective = InterceptorPayloads.cast(payloadAndHeaders.getPayload(), org.a2aproject.sdk.grpc.CancelTaskRequestOrBuilder.class);
String httpResponseBody = sendPostRequest(Utils.buildBaseUrl(agentInterface, effective.getTenant()) + String.format("/tasks/%1s:cancel", effective.getId()), payloadAndHeaders);
String httpResponseBody = sendPostRequest(Utils.buildBaseUrl(agentInterface, effective.getTenant()) + String.format("/tasks/%1s:cancel", HttpEndpoint.pathSegment("taskId", effective.getId())), payloadAndHeaders);
org.a2aproject.sdk.grpc.Task.Builder responseBuilder = org.a2aproject.sdk.grpc.Task.newBuilder();
ProtoJsonUtils.mergeIgnoringUnknownFields(httpResponseBody, responseBuilder);
return ProtoUtils.FromProto.task(responseBuilder);
Expand Down Expand Up @@ -288,26 +291,22 @@ public ListTasksResult listTasks(ListTasksParams request, @Nullable ClientCallCo


private String buildListTasksQueryString(org.a2aproject.sdk.grpc.ListTasksRequestOrBuilder request, ListTasksParams original) {
java.util.List<String> queryParts = new java.util.ArrayList<>();
List<String> queryParts = new ArrayList<>();
if (!request.getContextId().isEmpty() || "".equals(original.contextId())) {
queryParts.add("contextId=" + URLEncoder.encode(request.getContextId(), StandardCharsets.UTF_8));
}
// Proto3 does not distinguish an explicitly set default status from a cleared status.
if (request.getStatus() != org.a2aproject.sdk.grpc.TaskState.TASK_STATE_UNSPECIFIED
|| original.status() == org.a2aproject.sdk.spec.TaskState.TASK_STATE_UNSPECIFIED) {
queryParts.add("status=" + URLEncoder.encode(request.getStatus().toString(), StandardCharsets.UTF_8));
}
if (request.hasPageSize()) {
queryParts.add("pageSize=" + request.getPageSize());
}
if (!request.getPageToken().isEmpty() || "".equals(original.pageToken())) {
queryParts.add("pageToken=" + URLEncoder.encode(request.getPageToken(), StandardCharsets.UTF_8));
}
addPagination(queryParts, request.hasPageSize() ? request.getPageSize() : null, request.getPageToken());
if (request.hasHistoryLength()) {
queryParts.add("historyLength=" + request.getHistoryLength());
}
if (request.hasStatusTimestampAfter()) {
var timestamp = request.getStatusTimestampAfter();
var instant = java.time.Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos());
var instant = Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos());
queryParts.add("statusTimestampAfter=" + URLEncoder.encode(instant.toString(), StandardCharsets.UTF_8));
}
if (request.hasIncludeArtifacts()) {
Expand All @@ -316,15 +315,20 @@ private String buildListTasksQueryString(org.a2aproject.sdk.grpc.ListTasksReques
return String.join("&", queryParts);
}

private String buildListPushNotificationConfigsQueryString(ListTaskPushNotificationConfigsParams request) {
java.util.List<String> queryParts = new java.util.ArrayList<>();
if (request.pageSize() > 0) {
queryParts.add("pageSize=" + request.pageSize());
private String buildListPushNotificationConfigsQueryString(org.a2aproject.sdk.grpc.ListTaskPushNotificationConfigsRequestOrBuilder request) {
List<String> queryParts = new ArrayList<>();
addPagination(queryParts, request.getPageSize() > 0 ? request.getPageSize() : null, request.getPageToken());
return String.join("&", queryParts);
}

// Protobuf getters return an empty string for an unset page token, never null.
private static void addPagination(List<String> queryParts, @Nullable Integer pageSize, String pageToken) {
Comment thread
ehsavoie marked this conversation as resolved.
Resolved
if (pageSize != null) {
queryParts.add("pageSize=" + pageSize);
}
if (request.pageToken() != null && !request.pageToken().isEmpty()) {
queryParts.add("pageToken=" + URLEncoder.encode(request.pageToken(), StandardCharsets.UTF_8));
if (!pageToken.isEmpty()) {
queryParts.add("pageToken=" + URLEncoder.encode(pageToken, StandardCharsets.UTF_8));
}
return String.join("&", queryParts);
}

@Override
Expand All @@ -335,7 +339,7 @@ public TaskPushNotificationConfig createTaskPushNotificationConfiguration(TaskPu
PayloadAndHeaders payloadAndHeaders = applyInterceptors(SET_TASK_PUSH_NOTIFICATION_CONFIG_METHOD, builder, agentCard, context);
try {
org.a2aproject.sdk.grpc.TaskPushNotificationConfigOrBuilder effective = InterceptorPayloads.cast(payloadAndHeaders.getPayload(), org.a2aproject.sdk.grpc.TaskPushNotificationConfigOrBuilder.class);
String httpResponseBody = sendPostRequest(Utils.buildBaseUrl(agentInterface, effective.getTenant()) + String.format("/tasks/%1s/pushNotificationConfigs", effective.getTaskId()), payloadAndHeaders);
String httpResponseBody = sendPostRequest(Utils.buildBaseUrl(agentInterface, effective.getTenant()) + String.format("/tasks/%1s/pushNotificationConfigs", HttpEndpoint.pathSegment("taskId", effective.getTaskId())), payloadAndHeaders);
org.a2aproject.sdk.grpc.TaskPushNotificationConfig.Builder responseBuilder = org.a2aproject.sdk.grpc.TaskPushNotificationConfig.newBuilder();
ProtoJsonUtils.mergeIgnoringUnknownFields(httpResponseBody, responseBuilder);
return ProtoUtils.FromProto.taskPushNotificationConfig(responseBuilder);
Expand All @@ -352,7 +356,7 @@ public TaskPushNotificationConfig getTaskPushNotificationConfiguration(GetTaskPu
org.a2aproject.sdk.grpc.GetTaskPushNotificationConfigRequest.Builder builder
= org.a2aproject.sdk.grpc.GetTaskPushNotificationConfigRequest.newBuilder();
builder.setTaskId(request.taskId());
if (request.id() != null) {
if (request.id() != null && !request.id().isEmpty()) {
builder.setId(request.id());
}
if (request.tenant() != null) {
Expand All @@ -365,9 +369,9 @@ public TaskPushNotificationConfig getTaskPushNotificationConfiguration(GetTaskPu
StringBuilder url = new StringBuilder(Utils.buildBaseUrl(agentInterface, effective.getTenant()));
String configId = effective.getId();
if (!configId.isEmpty()) {
url.append(String.format("/tasks/%1s/pushNotificationConfigs/%2s", effective.getTaskId(), configId));
url.append(String.format("/tasks/%1s/pushNotificationConfigs/%2s", HttpEndpoint.pathSegment("taskId", effective.getTaskId()), HttpEndpoint.pathSegment("configId", configId)));
} else {
url.append(String.format("/tasks/%1s/pushNotificationConfigs/", effective.getTaskId()));
url.append(String.format("/tasks/%1s/pushNotificationConfigs/", HttpEndpoint.pathSegment("taskId", effective.getTaskId())));
}
A2AHttpClient.GetBuilder getBuilder = httpClient.createGet().url(url.toString());
addStandardHeaders(getBuilder, payloadAndHeaders);
Expand Down Expand Up @@ -406,8 +410,8 @@ public ListTaskPushNotificationConfigsResult listTaskPushNotificationConfigurati
try {
org.a2aproject.sdk.grpc.ListTaskPushNotificationConfigsRequestOrBuilder effective = InterceptorPayloads.cast(payloadAndHeaders.getPayload(), org.a2aproject.sdk.grpc.ListTaskPushNotificationConfigsRequestOrBuilder.class);
StringBuilder urlBuilder = new StringBuilder(Utils.buildBaseUrl(agentInterface, effective.getTenant()));
urlBuilder.append(String.format("/tasks/%1s/pushNotificationConfigs", effective.getTaskId()));
String queryString = buildListPushNotificationConfigsQueryString(ProtoUtils.FromProto.listTaskPushNotificationConfigsParams(effective));
urlBuilder.append(String.format("/tasks/%1s/pushNotificationConfigs", HttpEndpoint.pathSegment("taskId", effective.getTaskId())));
String queryString = buildListPushNotificationConfigsQueryString(effective);
if (!queryString.isEmpty()) {
urlBuilder.append("?").append(queryString);
}
Expand Down Expand Up @@ -439,7 +443,7 @@ public void deleteTaskPushNotificationConfigurations(DeleteTaskPushNotificationC
agentCard, context);
try {
org.a2aproject.sdk.grpc.DeleteTaskPushNotificationConfigRequestOrBuilder effective = InterceptorPayloads.cast(payloadAndHeaders.getPayload(), org.a2aproject.sdk.grpc.DeleteTaskPushNotificationConfigRequestOrBuilder.class);
String url = Utils.buildBaseUrl(agentInterface, effective.getTenant()) + String.format("/tasks/%1s/pushNotificationConfigs/%2s", effective.getTaskId(), effective.getId());
String url = Utils.buildBaseUrl(agentInterface, effective.getTenant()) + String.format("/tasks/%1s/pushNotificationConfigs/%2s", HttpEndpoint.pathSegment("taskId", effective.getTaskId()), HttpEndpoint.pathSegment("configId", effective.getId()));
A2AHttpClient.DeleteBuilder deleteBuilder = httpClient.createDelete().url(url);
addStandardHeaders(deleteBuilder, payloadAndHeaders);
A2AHttpResponse response = deleteBuilder.delete();
Expand Down Expand Up @@ -468,7 +472,7 @@ public void subscribeToTask(TaskIdParams request, Consumer<StreamingEventKind> e
SSEEventListener sseEventListener = new SSEEventListener(eventConsumer, errorConsumer);
try {
org.a2aproject.sdk.grpc.SubscribeToTaskRequestOrBuilder effective = InterceptorPayloads.cast(payloadAndHeaders.getPayload(), org.a2aproject.sdk.grpc.SubscribeToTaskRequestOrBuilder.class);
String url = Utils.buildBaseUrl(agentInterface, effective.getTenant()) + String.format("/tasks/%1s:subscribe", effective.getId());
String url = Utils.buildBaseUrl(agentInterface, effective.getTenant()) + String.format("/tasks/%1s:subscribe", HttpEndpoint.pathSegment("taskId", effective.getId()));
A2AHttpClient.PostBuilder postBuilder = createPostBuilder(url, payloadAndHeaders, false);
var streamFuture = streams.track(postBuilder.postAsyncSSE(
event -> sseEventListener.onMessage(event, ref.get()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,9 @@ public PayloadAndHeaders intercept(
assertEquals(
"POST /defaulttenant/tasks/changed/pushNotificationConfigs",
queue.poll(5, TimeUnit.SECONDS));
c.createTaskPushNotificationConfiguration(
TaskPushNotificationConfig.builder().url("https://example.com").build(), null);
assertEquals("POST /defaulttenant/tasks/changed/pushNotificationConfigs", queue.poll(5, TimeUnit.SECONDS));
ClientCallInterceptor clear =
new ClientCallInterceptor() {
@Override
Expand All @@ -258,14 +261,16 @@ public PayloadAndHeaders intercept(
if (payload
instanceof
org.a2aproject.sdk.grpc.ListTasksRequest.Builder b)
b.clearHistoryLength().clearIncludeArtifacts();
b.clearContextId().clearStatus().clearPageToken()
.clearHistoryLength().clearIncludeArtifacts();
return new PayloadAndHeaders(payload, headers);
}
};
var cleared = new RestTransport(null, card, iface, List.of(clear));
cleared.getTask(new TaskQueryParams("orig", 5), null);
assertEquals("GET /defaulttenant/tasks/orig", queue.poll(5, TimeUnit.SECONDS));
var list = new ListTasksParams(null, null, null, null, 5, null, true, null);
var list = new ListTasksParams("original", org.a2aproject.sdk.spec.TaskState.TASK_STATE_WORKING,
null, "cursor", 5, null, true, null);
cleared.listTasks(list, null);
assertEquals("GET /defaulttenant/tasks", queue.poll(5, TimeUnit.SECONDS));
var plain = new RestTransport(null, card, iface, null);
Expand All @@ -280,9 +285,9 @@ public PayloadAndHeaders intercept(
null,
null);
plain.listTasks(explicitDefaults, null);
assertEquals(
"GET /defaulttenant/tasks?contextId=&status=TASK_STATE_UNSPECIFIED&pageToken=",
queue.poll(5, TimeUnit.SECONDS));
assertEquals("GET /defaulttenant/tasks?contextId=&status=TASK_STATE_UNSPECIFIED", queue.poll(5, TimeUnit.SECONDS));
cleared.listTasks(explicitDefaults, null);
assertEquals("GET /defaulttenant/tasks?contextId=&status=TASK_STATE_UNSPECIFIED", queue.poll(5, TimeUnit.SECONDS));
ClientCallInterceptor nullPayload =
new ClientCallInterceptor() {
@Override
Expand Down
21 changes: 19 additions & 2 deletions common/src/main/java/org/a2aproject/sdk/util/Assert.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,31 @@ public static boolean isNullOrEmpty(@Nullable String value) {
public static <T> @NotNull T checkNotNullParam(String name, @Nullable T value) throws IllegalArgumentException {
checkNotNullParamChecked("name", name);
if (value == null) {
throw new IllegalArgumentException("Parameter '" + name + "' may not be null");
throw new IllegalArgumentException("Parameter '%s' may not be null".formatted(name));
}
return value;
}

/**
* Validates an identifier usable as a single resource path segment across transports.
*
* @param name name of the identifier being checked
* @param value identifier to validate
* @return the validated identifier
* @throws IllegalArgumentException if the identifier is empty or ambiguous
*/
public static String checkResourceId(String name, @Nullable String value) {
if (value == null || value.isEmpty() || value.equals(".") || value.equals("..")
|| value.indexOf('/') >= 0 || value.indexOf('\\') >= 0
|| value.indexOf('?') >= 0 || value.indexOf('#') >= 0) {
throw new IllegalArgumentException("Invalid identifier for '%s'".formatted(name));
}
return value;
}

private static <T> void checkNotNullParamChecked(final String name, final @Nullable T value) {
if (value == null) {
throw new IllegalArgumentException("Parameter '" + name + "' may not be null");
throw new IllegalArgumentException("Parameter '%s' may not be null".formatted(name));
}
}

Expand Down
Loading
Loading