-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathAsyncHelper.java
More file actions
67 lines (58 loc) · 2.08 KB
/
Copy pathAsyncHelper.java
File metadata and controls
67 lines (58 loc) · 2.08 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
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.agentstudio.resource;
import com.alibaba.dashscope.agentstudio.AgentStudioException;
import com.alibaba.dashscope.api.GeneralApi;
import com.alibaba.dashscope.base.HalfDuplexParamBase;
import com.alibaba.dashscope.common.DashScopeResult;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.protocol.ServiceOption;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
final class AsyncHelper {
private AsyncHelper() {}
static CompletableFuture<DashScopeResult> callAsync(
GeneralApi<HalfDuplexParamBase> api, HalfDuplexParamBase param, ServiceOption opt) {
CompletableFuture<DashScopeResult> future = new CompletableFuture<>();
try {
api.call(
param,
opt,
new ResultCallback<DashScopeResult>() {
@Override
public void onEvent(DashScopeResult result) {
future.complete(result);
}
@Override
public void onComplete() {}
@Override
public void onError(Exception e) {
future.completeExceptionally(normalize(e));
}
});
} catch (Exception e) {
future.completeExceptionally(normalize(e));
}
return future;
}
/** Wrap {@link ApiException}s as the unified {@link AgentStudioException}. */
private static Throwable normalize(Throwable e) {
return e instanceof ApiException ? AgentStudioException.wrap((ApiException) e) : e;
}
static <T> CompletableFuture<T> failedFuture(Throwable ex) {
CompletableFuture<T> f = new CompletableFuture<>();
f.completeExceptionally(ex);
return f;
}
static <T> T joinAndUnwrap(CompletableFuture<T> future) {
try {
return future.join();
} catch (CompletionException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
throw new ApiException(cause);
}
}
}