From c05024d450e9da88d31d94d451303efb06351423 Mon Sep 17 00:00:00 2001 From: swen Date: Sun, 15 Dec 2019 09:46:00 +0100 Subject: [PATCH] Improved async call to okhttp. Former solution just wrapped a blocking call, now we using asynch call and collect the results via callbacks. Mono's are created based on the result. This make more efficient use of the resources since nothing is blocking now. Reformatted according new checkstyle --- sdk/checkstyle-java.xml | 268 +++++++++++++++ sdk/pom.xml | 6 +- .../io/dapr/actors/AbstractClientBuilder.java | 66 ++-- .../io/dapr/actors/AbstractDaprClient.java | 250 ++++++++------ sdk/src/main/java/io/dapr/actors/ActorId.java | 255 +++++++------- .../main/java/io/dapr/actors/ActorTrace.java | 24 +- .../main/java/io/dapr/actors/Constants.java | 133 ++++--- .../main/java/io/dapr/actors/DaprError.java | 121 +++---- .../java/io/dapr/actors/DaprException.java | 92 ++--- .../actors/client/ActorProxyAsyncClient.java | 20 +- .../client/ActorProxyClientBuilder.java | 30 +- .../client/ActorProxyHttpAsyncClient.java | 37 +- .../io/dapr/actors/runtime/AbstractActor.java | 23 +- .../java/io/dapr/actors/runtime/Actor.java | 24 +- .../io/dapr/actors/runtime/ActorCallType.java | 52 ++- .../io/dapr/actors/runtime/ActorManager.java | 6 +- .../actors/runtime/ActorMethodContext.java | 158 ++++----- .../io/dapr/actors/runtime/ActorRuntime.java | 317 +++++++++-------- .../io/dapr/actors/runtime/ActorService.java | 5 +- .../runtime/ActorStateProviderSerializer.java | 88 ++--- .../io/dapr/actors/runtime/ActorType.java | 39 +-- .../actors/runtime/ActorTypeInformation.java | 324 +++++++++--------- .../actors/runtime/ActorTypeUtilities.java | 178 +++++----- .../actors/runtime/AppToDaprAsyncClient.java | 108 +++--- .../runtime/AppToDaprClientBuilder.java | 30 +- .../runtime/AppToDaprHttpAsyncClient.java | 118 ++++--- .../io/dapr/actors/runtime/Remindable.java | 23 +- .../test/java/io/dapr/actors/ActorIdTest.java | 130 ++++--- .../actors/client/DaprHttpAsyncClientIT.java | 46 +-- 29 files changed, 1649 insertions(+), 1322 deletions(-) create mode 100644 sdk/checkstyle-java.xml diff --git a/sdk/checkstyle-java.xml b/sdk/checkstyle-java.xml new file mode 100644 index 0000000000..668dc1fe8f --- /dev/null +++ b/sdk/checkstyle-java.xml @@ -0,0 +1,268 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/sdk/pom.xml b/sdk/pom.xml index 5cbf8e37cc..6ef230cdd9 100644 --- a/sdk/pom.xml +++ b/sdk/pom.xml @@ -1,7 +1,7 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 diff --git a/sdk/src/main/java/io/dapr/actors/AbstractClientBuilder.java b/sdk/src/main/java/io/dapr/actors/AbstractClientBuilder.java index 5af3cc78ac..c5eaf7fe9f 100644 --- a/sdk/src/main/java/io/dapr/actors/AbstractClientBuilder.java +++ b/sdk/src/main/java/io/dapr/actors/AbstractClientBuilder.java @@ -2,48 +2,46 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors; -import okhttp3.OkHttpClient; -import io.dapr.actors.*; - /** * Base class for client builders */ public abstract class AbstractClientBuilder { - /** - * Default port for Dapr after checking environment variable. - */ - private int port = AbstractClientBuilder.GetEnvPortOrDefault(); - - /** - * Overrides the port. - * @param port New port. - * @return This instance. - */ - public AbstractClientBuilder withPort(int port) { - this.port = port; - return this; + /** + * Default port for Dapr after checking environment variable. + */ + private int port = AbstractClientBuilder.GetEnvPortOrDefault(); + + /** + * Overrides the port. + * + * @param port New port. + * @return This instance. + */ + public AbstractClientBuilder withPort(int port) { + this.port = port; + return this; + } + + /** + * Tries to get a valid port from environment variable or returns default. + * + * @return Port defined in env variable or default. + */ + protected static int GetEnvPortOrDefault() { + String envPort = System.getenv(Constants.ENV_DAPR_HTTP_PORT); + if (envPort == null) { + return Constants.DEFAULT_PORT; } - /** - * Tries to get a valid port from environment variable or returns default. - * @return Port defined in env variable or default. - */ - protected static int GetEnvPortOrDefault() { - String envPort = System.getenv(Constants.ENV_DAPR_HTTP_PORT); - if (envPort == null) { - return Constants.DEFAULT_PORT; - } - - try { - return Integer.parseInt(envPort.trim()); - } catch (NumberFormatException e) { - e.printStackTrace(); - } - - return Constants.DEFAULT_PORT; + try { + return Integer.parseInt(envPort.trim()); + } catch (NumberFormatException e) { + e.printStackTrace(); } + + return Constants.DEFAULT_PORT; + } } diff --git a/sdk/src/main/java/io/dapr/actors/AbstractDaprClient.java b/sdk/src/main/java/io/dapr/actors/AbstractDaprClient.java index f5a687350d..10ffb5f269 100644 --- a/sdk/src/main/java/io/dapr/actors/AbstractDaprClient.java +++ b/sdk/src/main/java/io/dapr/actors/AbstractDaprClient.java @@ -1,119 +1,173 @@ package io.dapr.actors; - import com.fasterxml.jackson.databind.ObjectMapper; -import okhttp3.*; -import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; - import java.io.IOException; import java.net.URL; import java.util.UUID; +import okhttp3.*; +import reactor.core.publisher.Mono; // base class of hierarchy public abstract class AbstractDaprClient { - /** - * Defines the standard application/json type for HTTP calls in Dapr. - */ - private static final MediaType MEDIA_TYPE_APPLICATION_JSON = MediaType.get("application/json; charset=utf-8"); - - /** - * Shared object representing an empty request body in JSON. - */ - private static final RequestBody REQUEST_BODY_EMPTY_JSON = RequestBody.create(MEDIA_TYPE_APPLICATION_JSON, ""); - - /** - * JSON Object Mapper. - */ - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - /** - * The base url used for form urls. This is typically "http://localhost:3500". - */ - private final String baseUrl; - - /** - * Http client used for all API calls. - */ - private final OkHttpClient httpClient; - - /** - * Creates a new instance of {@link AbstractDaprClient}. - * @param port Port for calling Dapr. (e.g. 3500) - * @param httpClient RestClient used for all API calls in this new instance. - */ - public AbstractDaprClient(int port, OkHttpClient httpClient) - { - this.baseUrl = String.format("http://%s:%d/", Constants.DEFAULT_HOSTNAME, port);; - this.httpClient = httpClient; + /** + * Defines the standard application/json type for HTTP calls in Dapr. + */ + private static final MediaType MEDIA_TYPE_APPLICATION_JSON = MediaType.get("application/json; charset=utf-8"); + + /** + * Shared object representing an empty request body in JSON. + */ + private static final RequestBody REQUEST_BODY_EMPTY_JSON = RequestBody.create(MEDIA_TYPE_APPLICATION_JSON, ""); + + /** + * JSON Object Mapper. + */ + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + /** + * The base url used for form urls. This is typically "http://localhost:3500". + */ + private final String baseUrl; + + /** + * Http client used for all API calls. + */ + private final OkHttpClient httpClient; + + /** + * Creates a new instance of {@link AbstractDaprClient}. + * + * @param port Port for calling Dapr. (e.g. 3500) + * @param httpClient RestClient used for all API calls in this new instance. + */ + public AbstractDaprClient(int port, OkHttpClient httpClient) { + this.baseUrl = String.format("http://%s:%d/", Constants.DEFAULT_HOSTNAME, port);; + this.httpClient = httpClient; + } + + // common methods + /** + * Invokes an API asynchronously that returns Void. + * + * @param method HTTP method. + * @param urlString url as String. + * @param json JSON payload or null. + * @return Asynchronous Void + */ + protected final Mono invokeAPIVoid(String method, String urlString, String json) { + return this.invokeAPI(method, urlString, json).then(); + } + + /** + * Invokes an API asynchronously that returns a text payload. + * + * @param method HTTP method. + * @param urlString url as String. + * @param json JSON payload or null. + * @return Asynchronous text + */ + public final Mono invokeAPI(String method, String urlString, String json) throws RuntimeException { + + DaprHttpCallback cb = new DaprHttpCallback() { + + @Override + public void onFailure(Call call, Exception e) { + Mono.error(e); + } + + @Override + public void onSuccess(String response) { + Mono.just(response); + } + }; + try { + tryInvokeAPI(method, urlString, json, cb); + } catch (Exception e) { + throw new RuntimeException(e); + } + return Mono.empty(); + } + + /** + * Invokes an API synchronously and returns a text payload. + * + * @param method HTTP method. + * @param urlString url as String. + * @param json JSON payload or null. + * @return text + */ + private final void tryInvokeAPI(String method, String urlString, String json, final DaprHttpCallback cb) throws IOException, DaprException { + String requestId = UUID.randomUUID().toString(); + RequestBody body = json != null ? RequestBody.create(MEDIA_TYPE_APPLICATION_JSON, json) : REQUEST_BODY_EMPTY_JSON; + + Request request = new Request.Builder() + .url(new URL(this.baseUrl + urlString)) + .method(method, body) + .addHeader(Constants.HEADER_DAPR_REQUEST_ID, requestId) + .build(); + + this.httpClient.newCall(request).enqueue(new Callback() { + @Override + public void onFailure(Call call, IOException e) { + cb.onFailure(call, e); + } + + @Override + public void onResponse(Call call, Response response) throws IOException { + try (ResponseBody responseBody = response.body()) { + if (!response.isSuccessful()) { + DaprError error = parseDaprError(response.body().string()); + if ((error != null) && (error.getErrorCode() != null) && (error.getMessage() != null)) { + throw new DaprException(error); + } + } else { + cb.onSuccess(responseBody.toString()); + } + } + } + }); + + } + + /** + * Tries to parse an error from Dapr response body. + * + * @param json Response body from Dapr. + * @return DaprError or null if could not parse. + */ + protected static DaprError parseDaprError(String json) { + if (json == null) { + return null; } - // common methods - /** - * Invokes an API asynchronously that returns Void. - * @param method HTTP method. - * @param urlString url as String. - * @param json JSON payload or null. - * @return Asynchronous Void - */ - protected final Mono invokeAPIVoid(String method, String urlString, String json) { - return this.invokeAPI(method, urlString, json).then(); + try { + return OBJECT_MAPPER.readValue(json, DaprError.class); + } catch (IOException e) { + e.printStackTrace(); + return null; } + } + + public interface DaprHttpCallback { /** - * Invokes an API asynchronously that returns a text payload. - * @param method HTTP method. - * @param urlString url as String. - * @param json JSON payload or null. - * @return Asynchronous text + * called when the server response was not 2xx or when an exception was + * thrown in the process + * + * @param response - in case of server error (4xx, 5xx) this contains the + * server response in case of IO exception this is null + * @param throwable - contains the exception. in case of server error (4xx, + * 5xx) this is null */ - protected final Mono invokeAPI(String method, String urlString, String json) { - String requestId = UUID.randomUUID().toString(); - RequestBody body = json != null ? RequestBody.create(json, MEDIA_TYPE_APPLICATION_JSON) : REQUEST_BODY_EMPTY_JSON; - - // use Mono blocking wrapper to be reactive - Mono blockingWrapper = Mono.fromCallable(() -> { - Request request = new Request.Builder() - .url(new URL(this.baseUrl + urlString)) - .method(method, body) - .addHeader(Constants.HEADER_DAPR_REQUEST_ID, requestId) - .build(); - - - try(Response response = this.httpClient.newCall(request).execute()) - { - if (!response.isSuccessful()) { - DaprError error = parseDaprError(response.body().string()); - if ((error != null) && (error.getErrorCode() != null) && (error.getMessage() != null)) { - throw new DaprException(error); - } - - throw new DaprException("UNKNOWN", String.format("Dapr's Actor API %s failed with return code %d %s", urlString, response.code())); - } - - return response.body().string(); - } - }); - - return blockingWrapper.subscribeOn(Schedulers.boundedElastic()); - } - + public void onFailure(Call call, Exception e); /** - * Tries to parse an error from Dapr response body. - * @param json Response body from Dapr. - * @return DaprError or null if could not parse. + * contains the server response + * + * @param response */ - protected static DaprError parseDaprError(String json) { - if (json == null) { - return null; - } + public void onSuccess(String response); + } - try { - return OBJECT_MAPPER.readValue(json, DaprError.class); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } } diff --git a/sdk/src/main/java/io/dapr/actors/ActorId.java b/sdk/src/main/java/io/dapr/actors/ActorId.java index 8dbce62683..4148aa1f8f 100644 --- a/sdk/src/main/java/io/dapr/actors/ActorId.java +++ b/sdk/src/main/java/io/dapr/actors/ActorId.java @@ -2,7 +2,6 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors; import java.util.UUID; @@ -12,139 +11,139 @@ */ public class ActorId extends Object implements Comparable { - /** - * The ID of the actor as a String. - */ - private final String stringId; - - /** - * An error message for an invalid constructor arg. - */ - private final String errorMsg = "actor needs to be initialized with an id!"; - - /** - * Initializes a new instance of the ActorId class with the id passed in. - * - * @param id Value for actor id - */ - public ActorId(String id) { - if (id != null) { - this.stringId = id; - } else { - throw new IllegalArgumentException(errorMsg); - } - } - - /** - * Returns the id of the actor as {link #java.lang.String} - * - * @return ActorID as {link #java.lang.String} - */ - public String getStringId() { - return this.stringId; - } - - /** - * Creates a new ActorId with a random id. - * - * @return A new ActorId with a random id. - */ - public static ActorId createRandom() { - UUID id = UUID.randomUUID(); - return new ActorId(id.toString()); - } - - /** - * Determines whether two specified actorIds have the same id. - * - * @param id1 The first actorId to compare, or null - * @param id2 The second actorId to compare, or null. - * @return true if the id is same for both objects; otherwise, false. - */ - static public boolean equals(ActorId id1, ActorId id2) { - if (id1 == null && id2 == null) { - return true; - } else if (id2 == null || id1 == null) { - return false; - } else { - return hasEqualContent(id1, id2); - } - } - - /** - * Compares this instance with a specified {link #ActorId} object and - * indicates whether this instance precedes, follows, or appears in the same - * position in the sort order as the specified actorId. - *

- * The comparison is done based on the id if both the instances. - * - * @param other The actorId to compare with this instance. - * @return A 32-bit signed integer that indicates whether this instance - * precedes, follows, or appears in the same position in the sort order as the - * other parameter. - */ - @Override - public int compareTo(ActorId other) { - return (other == null) ? 1 - : compareContent(this, other); + /** + * The ID of the actor as a String. + */ + private final String stringId; + + /** + * An error message for an invalid constructor arg. + */ + private final String errorMsg = "actor needs to be initialized with an id!"; + + /** + * Initializes a new instance of the ActorId class with the id passed in. + * + * @param id Value for actor id + */ + public ActorId(String id) { + if (id != null) { + this.stringId = id; + } else { + throw new IllegalArgumentException(errorMsg); } - - /** - * - * @param id1 - * @param id2 - * @return true if the two ActorId's are equal - */ - static private boolean hasEqualContent(ActorId id1, ActorId id2) { - return id1.getStringId().equalsIgnoreCase(id2.getStringId()); + } + + /** + * Returns the id of the actor as {link #java.lang.String} + * + * @return ActorID as {link #java.lang.String} + */ + public String getStringId() { + return this.stringId; + } + + /** + * Creates a new ActorId with a random id. + * + * @return A new ActorId with a random id. + */ + public static ActorId createRandom() { + UUID id = UUID.randomUUID(); + return new ActorId(id.toString()); + } + + /** + * Determines whether two specified actorIds have the same id. + * + * @param id1 The first actorId to compare, or null + * @param id2 The second actorId to compare, or null. + * @return true if the id is same for both objects; otherwise, false. + */ + static public boolean equals(ActorId id1, ActorId id2) { + if (id1 == null && id2 == null) { + return true; + } else if (id2 == null || id1 == null) { + return false; + } else { + return hasEqualContent(id1, id2); } - - /** - * - * @param id1 - * @param id2 - * @return -1, 0, or 1 depending on the compare result of the stringId member. - */ - private int compareContent(ActorId id1, ActorId id2) { - return id1.getStringId().compareToIgnoreCase(id2.getStringId()); + } + + /** + * Compares this instance with a specified {link #ActorId} object and + * indicates whether this instance precedes, follows, or appears in the same + * position in the sort order as the specified actorId. + *

+ * The comparison is done based on the id if both the instances. + * + * @param other The actorId to compare with this instance. + * @return A 32-bit signed integer that indicates whether this instance + * precedes, follows, or appears in the same position in the sort order as the + * other parameter. + */ + @Override + public int compareTo(ActorId other) { + return (other == null) ? 1 + : compareContent(this, other); + } + + /** + * + * @param id1 + * @param id2 + * @return true if the two ActorId's are equal + */ + static private boolean hasEqualContent(ActorId id1, ActorId id2) { + return id1.getStringId().equalsIgnoreCase(id2.getStringId()); + } + + /** + * + * @param id1 + * @param id2 + * @return -1, 0, or 1 depending on the compare result of the stringId member. + */ + private int compareContent(ActorId id1, ActorId id2) { + return id1.getStringId().compareToIgnoreCase(id2.getStringId()); + } + + /** + * + * @return The String representation of this ActorId + */ + @Override + public String toString() { + return this.stringId; + } + + /** + * + * @return The hash code of this ActorId + */ + @Override + public int hashCode() { + return this.stringId.hashCode(); + } + + /** + * + * @return true if the 2 ActorId's are equal. + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; } - /** - * - * @return The String representation of this ActorId - */ - @Override - public String toString() { - return this.stringId; + if (obj == null) { + return false; } - /** - * - * @return The hash code of this ActorId - */ - @Override - public int hashCode() { - return this.stringId.hashCode(); + if (getClass() != obj.getClass()) { + return false; } - /** - * - * @return true if the 2 ActorId's are equal. - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (obj == null) { - return false; - } - - if (getClass() != obj.getClass()) { - return false; - } - - return hasEqualContent(this, (ActorId) obj); - } + return hasEqualContent(this, (ActorId) obj); + } } diff --git a/sdk/src/main/java/io/dapr/actors/ActorTrace.java b/sdk/src/main/java/io/dapr/actors/ActorTrace.java index f3c7d5fea1..b3c61bbdeb 100644 --- a/sdk/src/main/java/io/dapr/actors/ActorTrace.java +++ b/sdk/src/main/java/io/dapr/actors/ActorTrace.java @@ -2,22 +2,22 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors; /** * Stub */ public class ActorTrace { - public static void WriteInfo(String text) { - System.out.println(text); - } - - public static void WriteWarning(String text) { - System.out.println("Warning: " + text); - } - - public static void WriteError(String text) { - System.err.println(text); - } + + public static void WriteInfo(String text) { + System.out.println(text); + } + + public static void WriteWarning(String text) { + System.out.println("Warning: " + text); + } + + public static void WriteError(String text) { + System.err.println(text); + } } diff --git a/sdk/src/main/java/io/dapr/actors/Constants.java b/sdk/src/main/java/io/dapr/actors/Constants.java index 86ea80fac8..c09014d02a 100644 --- a/sdk/src/main/java/io/dapr/actors/Constants.java +++ b/sdk/src/main/java/io/dapr/actors/Constants.java @@ -1,67 +1,66 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ - -package io.dapr.actors; - -/** - * Useful constants for the Dapr's Actor SDK. - */ -public final class Constants { - - /** - * Dapr API used in this client. - */ - public static final String API_VERSION = "v1.0"; - - /** - * Dapr's default hostname. - */ - public static final String DEFAULT_HOSTNAME = "localhost"; - - /** - * Dapr's default port. - */ - public static final int DEFAULT_PORT = 3500; - - /** - * Environment variable used to set Dapr's port. - */ - public static final String ENV_DAPR_HTTP_PORT = "DAPR_HTTP_PORT"; - - /** - * Header used for request id in Dapr. - */ - public static final String HEADER_DAPR_REQUEST_ID = "X-DaprRequestId"; - - /** - * Base URL for Dapr Actor APIs. - */ - private static String ACTORS_BASE_URL = API_VERSION + "/" + "actors"; - - /** - * String format for Actors state management relative url. - */ - public static String ACTOR_STATE_KEY_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/state/%s"; - - /** - * String format for Actors state management relative url. - */ - public static String ACTOR_STATE_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/state"; - - /** - * String format for Actors method invocation relative url. - */ - public static String ACTOR_METHOD_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/method/%s"; - - /** - * String format for Actors reminder registration relative url.. - */ - public static String ACTOR_REMINDER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/reminders/%s"; - - /** - * String format for Actors timer registration relative url.. - */ - public static String ACTOR_TIMER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/reminders/%s"; -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors; + +/** + * Useful constants for the Dapr's Actor SDK. + */ +public final class Constants { + + /** + * Dapr API used in this client. + */ + public static final String API_VERSION = "v1.0"; + + /** + * Dapr's default hostname. + */ + public static final String DEFAULT_HOSTNAME = "localhost"; + + /** + * Dapr's default port. + */ + public static final int DEFAULT_PORT = 3500; + + /** + * Environment variable used to set Dapr's port. + */ + public static final String ENV_DAPR_HTTP_PORT = "DAPR_HTTP_PORT"; + + /** + * Header used for request id in Dapr. + */ + public static final String HEADER_DAPR_REQUEST_ID = "X-DaprRequestId"; + + /** + * Base URL for Dapr Actor APIs. + */ + private static String ACTORS_BASE_URL = API_VERSION + "/" + "actors"; + + /** + * String format for Actors state management relative url. + */ + public static String ACTOR_STATE_KEY_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/state/%s"; + + /** + * String format for Actors state management relative url. + */ + public static String ACTOR_STATE_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/state"; + + /** + * String format for Actors method invocation relative url. + */ + public static String ACTOR_METHOD_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/method/%s"; + + /** + * String format for Actors reminder registration relative url.. + */ + public static String ACTOR_REMINDER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/reminders/%s"; + + /** + * String format for Actors timer registration relative url.. + */ + public static String ACTOR_TIMER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/reminders/%s"; +} diff --git a/sdk/src/main/java/io/dapr/actors/DaprError.java b/sdk/src/main/java/io/dapr/actors/DaprError.java index 682b14c62a..672d4a4e29 100644 --- a/sdk/src/main/java/io/dapr/actors/DaprError.java +++ b/sdk/src/main/java/io/dapr/actors/DaprError.java @@ -1,59 +1,62 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ - -package io.dapr.actors; - -/** - * Represents an error message from Dapr. - */ -class DaprError { - - /** - * Error code. - */ - private String errorCode; - - /** - * Error Message. - */ - private String message; - - /** - * Gets the error code. - * @return Error code. - */ - public String getErrorCode() { - return errorCode; - } - - /** - * Sets the error code. - * @param errorCode Error code. - * @return This instance. - */ - public DaprError setErrorCode(String errorCode) { - this.errorCode = errorCode; - return this; - } - - /** - * Gets the error message. - * @return Error message. - */ - public String getMessage() { - return message; - } - - /** - * Sets the error message. - * @param message Error message. - * @return This instance. - */ - public DaprError setMessage(String message) { - this.message = message; - return this; - } - -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors; + +/** + * Represents an error message from Dapr. + */ +class DaprError { + + /** + * Error code. + */ + private String errorCode; + + /** + * Error Message. + */ + private String message; + + /** + * Gets the error code. + * + * @return Error code. + */ + public String getErrorCode() { + return errorCode; + } + + /** + * Sets the error code. + * + * @param errorCode Error code. + * @return This instance. + */ + public DaprError setErrorCode(String errorCode) { + this.errorCode = errorCode; + return this; + } + + /** + * Gets the error message. + * + * @return Error message. + */ + public String getMessage() { + return message; + } + + /** + * Sets the error message. + * + * @param message Error message. + * @return This instance. + */ + public DaprError setMessage(String message) { + this.message = message; + return this; + } + +} diff --git a/sdk/src/main/java/io/dapr/actors/DaprException.java b/sdk/src/main/java/io/dapr/actors/DaprException.java index 50ad94a9b9..67c251f8cd 100644 --- a/sdk/src/main/java/io/dapr/actors/DaprException.java +++ b/sdk/src/main/java/io/dapr/actors/DaprException.java @@ -1,45 +1,47 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ - -package io.dapr.actors; - -import java.io.IOException; - -/** - * A Dapr's specific exception. - */ -public class DaprException extends IOException { - - /** - * Dapr's error code for this exception. - */ - private String errorCode; - - /** - * New exception from a server-side generated error code and message. - * @param daprError Server-side error. - */ - DaprException(DaprError daprError) { - this(daprError.getErrorCode(), daprError.getMessage()); - } - - /** - * New Exception from a client-side generated error code and message. - * @param errorCode Client-side error code. - * @param message Client-side error message. - */ - DaprException(String errorCode, String message) { - super(String.format("%s: %s", errorCode, message)); - this.errorCode = errorCode; - } - - /** - * Returns the exception's error code. - * @return Error code. - */ - public String getErrorCode() { - return this.errorCode; - } -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors; + +import java.io.IOException; + +/** + * A Dapr's specific exception. + */ +public class DaprException extends IOException { + + /** + * Dapr's error code for this exception. + */ + private String errorCode; + + /** + * New exception from a server-side generated error code and message. + * + * @param daprError Server-side error. + */ + DaprException(DaprError daprError) { + this(daprError.getErrorCode(), daprError.getMessage()); + } + + /** + * New Exception from a client-side generated error code and message. + * + * @param errorCode Client-side error code. + * @param message Client-side error message. + */ + DaprException(String errorCode, String message) { + super(String.format("%s: %s", errorCode, message)); + this.errorCode = errorCode; + } + + /** + * Returns the exception's error code. + * + * @return Error code. + */ + public String getErrorCode() { + return this.errorCode; + } +} diff --git a/sdk/src/main/java/io/dapr/actors/client/ActorProxyAsyncClient.java b/sdk/src/main/java/io/dapr/actors/client/ActorProxyAsyncClient.java index b4f6b0bfda..b86e3d6950 100644 --- a/sdk/src/main/java/io/dapr/actors/client/ActorProxyAsyncClient.java +++ b/sdk/src/main/java/io/dapr/actors/client/ActorProxyAsyncClient.java @@ -2,7 +2,6 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors.client; import reactor.core.publisher.Mono; @@ -12,13 +11,14 @@ */ interface ActorProxyAsyncClient { - /** - * Invokes an Actor method on Dapr. - * @param actorType Type of actor. - * @param actorId Actor Identifier. - * @param methodName Method name to invoke. - * @param jsonPayload Serialized body. - * @return Asynchronous result with the Actor's response. - */ - Mono invokeActorMethod(String actorType, String actorId, String methodName, String jsonPayload); + /** + * Invokes an Actor method on Dapr. + * + * @param actorType Type of actor. + * @param actorId Actor Identifier. + * @param methodName Method name to invoke. + * @param jsonPayload Serialized body. + * @return Asynchronous result with the Actor's response. + */ + Mono invokeActorMethod(String actorType, String actorId, String methodName, String jsonPayload); } diff --git a/sdk/src/main/java/io/dapr/actors/client/ActorProxyClientBuilder.java b/sdk/src/main/java/io/dapr/actors/client/ActorProxyClientBuilder.java index 4f7d88fb9f..514776af33 100644 --- a/sdk/src/main/java/io/dapr/actors/client/ActorProxyClientBuilder.java +++ b/sdk/src/main/java/io/dapr/actors/client/ActorProxyClientBuilder.java @@ -2,29 +2,29 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors.client; -import okhttp3.OkHttpClient; import io.dapr.actors.*; +import okhttp3.OkHttpClient; /** * Builds an instance of ActorProxyAsyncClient. */ class ActorProxyClientBuilder extends AbstractClientBuilder { - /** - * Default port for Dapr after checking environment variable. - */ - private int port = ActorProxyClientBuilder.GetEnvPortOrDefault(); + /** + * Default port for Dapr after checking environment variable. + */ + private int port = ActorProxyClientBuilder.GetEnvPortOrDefault(); - /** - * Builds an async client. - * @return Builds an async client. - */ - public ActorProxyAsyncClient buildAsyncClient() { - OkHttpClient.Builder builder = new OkHttpClient.Builder(); - // TODO: Expose configurations for OkHttpClient or com.microsoft.rest.RestClient. - return new ActorProxyHttpAsyncClient(this.port, builder.build()); - } + /** + * Builds an async client. + * + * @return Builds an async client. + */ + public ActorProxyAsyncClient buildAsyncClient() { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + // TODO: Expose configurations for OkHttpClient or com.microsoft.rest.RestClient. + return new ActorProxyHttpAsyncClient(this.port, builder.build()); + } } diff --git a/sdk/src/main/java/io/dapr/actors/client/ActorProxyHttpAsyncClient.java b/sdk/src/main/java/io/dapr/actors/client/ActorProxyHttpAsyncClient.java index 2b44b35eab..482712407d 100644 --- a/sdk/src/main/java/io/dapr/actors/client/ActorProxyHttpAsyncClient.java +++ b/sdk/src/main/java/io/dapr/actors/client/ActorProxyHttpAsyncClient.java @@ -2,11 +2,9 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors.client; import io.dapr.actors.*; -import io.dapr.actors.AbstractDaprClient; import okhttp3.*; import reactor.core.publisher.Mono; @@ -14,22 +12,23 @@ * Http client to call actors methods. */ class ActorProxyHttpAsyncClient extends AbstractDaprClient implements ActorProxyAsyncClient { - /** - * Creates a new instance of {@link ActorProxyHttpAsyncClient}. - * @param port Port for calling Dapr. (e.g. 3500) - * @param httpClient RestClient used for all API calls in this new instance. - */ - public ActorProxyHttpAsyncClient(int port, OkHttpClient httpClient) - { - super(port, httpClient); - } - /** - * {@inheritDoc} - */ - @Override - public Mono invokeActorMethod(String actorType, String actorId, String methodName, String jsonPayload) { - String url = String.format(Constants.ACTOR_METHOD_RELATIVE_URL_FORMAT, actorType, actorId, methodName); - return super.invokeAPI("PUT", url, jsonPayload); - } + /** + * Creates a new instance of {@link ActorProxyHttpAsyncClient}. + * + * @param port Port for calling Dapr. (e.g. 3500) + * @param httpClient RestClient used for all API calls in this new instance. + */ + public ActorProxyHttpAsyncClient(int port, OkHttpClient httpClient) { + super(port, httpClient); + } + + /** + * {@inheritDoc} + */ + @Override + public Mono invokeActorMethod(String actorType, String actorId, String methodName, String jsonPayload) { + String url = String.format(Constants.ACTOR_METHOD_RELATIVE_URL_FORMAT, actorType, actorId, methodName); + return super.invokeAPI("PUT", url, jsonPayload); + } } diff --git a/sdk/src/main/java/io/dapr/actors/runtime/AbstractActor.java b/sdk/src/main/java/io/dapr/actors/runtime/AbstractActor.java index 1162c254f2..5f58e6185a 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/AbstractActor.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/AbstractActor.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ - -package io.dapr.actors.runtime; - -/** - * TODO - this is the base class Actor implementations (user code) will extend. - */ -public abstract class AbstractActor { -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors.runtime; + +/** + * TODO - this is the base class Actor implementations (user code) will extend. + */ +public abstract class AbstractActor { +} diff --git a/sdk/src/main/java/io/dapr/actors/runtime/Actor.java b/sdk/src/main/java/io/dapr/actors/runtime/Actor.java index abc4af567e..ea13bd6448 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/Actor.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/Actor.java @@ -1,12 +1,12 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ - -package io.dapr.actors.runtime; - -/** - * TODO - this is the interface user Actor methods should implement to receive calls. - */ -public interface Actor { -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors.runtime; + +/** + * TODO - this is the interface user Actor methods should implement to receive + * calls. + */ +public interface Actor { +} diff --git a/sdk/src/main/java/io/dapr/actors/runtime/ActorCallType.java b/sdk/src/main/java/io/dapr/actors/runtime/ActorCallType.java index b382e11340..a57ebea7a0 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/ActorCallType.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/ActorCallType.java @@ -1,27 +1,25 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ - -package io.dapr.actors.runtime; - -/** - * Represents the call-type associated with the method invoked by actor runtime. - */ -enum ActorCallType { - - /** - * Specifies that the method invoked is an actor interface method for a given client request. - */ - ACTOR_INTERFACE_METHOD, - - /** - * Specifies that the method invoked is a timer callback method. - */ - TIMER_METHOD, - - /** - * Specifies that the method is when a reminder fires. - */ - REMINDER_METHOD -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors.runtime; + +/** + * Represents the call-type associated with the method invoked by actor runtime. + */ +enum ActorCallType { + + /** + * Specifies that the method invoked is an actor interface method for a given + * client request. + */ + ACTOR_INTERFACE_METHOD, + /** + * Specifies that the method invoked is a timer callback method. + */ + TIMER_METHOD, + /** + * Specifies that the method is when a reminder fires. + */ + REMINDER_METHOD +} diff --git a/sdk/src/main/java/io/dapr/actors/runtime/ActorManager.java b/sdk/src/main/java/io/dapr/actors/runtime/ActorManager.java index 3974dd43a6..c42bcb2cc3 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/ActorManager.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/ActorManager.java @@ -3,9 +3,7 @@ // stub public class ActorManager { - public ActorManager(ActorService actorService) { + public ActorManager(ActorService actorService) { - } + } } - - diff --git a/sdk/src/main/java/io/dapr/actors/runtime/ActorMethodContext.java b/sdk/src/main/java/io/dapr/actors/runtime/ActorMethodContext.java index 3fcff78b41..cd841d7fe0 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/ActorMethodContext.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/ActorMethodContext.java @@ -1,78 +1,80 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ - -package io.dapr.actors.runtime; - -/** - * Contains information about the method that is invoked by actor runtime. - */ -class ActorMethodContext { - - /** - * Method name to be invoked. - */ - private final String methodName; - - /** - * Call type to be used. - */ - private final ActorCallType callType; - - /** - * Constructs a new instance of {@link ActorMethodContext} - * @param methodName Method name to be invoked. - * @param callType Call type to be used. - */ - private ActorMethodContext(String methodName, ActorCallType callType) { - this.methodName = methodName; - this.callType = callType; - } - - /** - * Gets the name of the method invoked by actor runtime. - * @return The method name. - */ - public String getMethodName() { - return this.methodName; - } - - /** - * Gets the call type to be used. - * @return Call type. - */ - public ActorCallType getCallType() { - return this.callType; - } - - /** - * Creates a context to invoke an Actor's method. - * @param methodName THe method to be invoked. - * @return Context of the method call as {@link ActorMethodContext} - */ - static ActorMethodContext CreateForActor(String methodName) - { - return new ActorMethodContext(methodName, ActorCallType.ACTOR_INTERFACE_METHOD); - } - - /** - * Creates a context to invoke an Actor's timer. - * @param methodName THe method to be invoked. - * @return Context of the method call as {@link ActorMethodContext} - */ - static ActorMethodContext CreateForTimer(String methodName) - { - return new ActorMethodContext(methodName, ActorCallType.TIMER_METHOD); - } - - /** - * Creates a context to invoke an Actor's reminder. - * @param methodName THe method to be invoked. - * @return Context of the method call as {@link ActorMethodContext} - */ - static ActorMethodContext CreateForReminder(String methodName) - { - return new ActorMethodContext(methodName, ActorCallType.REMINDER_METHOD); - } -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors.runtime; + +/** + * Contains information about the method that is invoked by actor runtime. + */ +class ActorMethodContext { + + /** + * Method name to be invoked. + */ + private final String methodName; + + /** + * Call type to be used. + */ + private final ActorCallType callType; + + /** + * Constructs a new instance of {@link ActorMethodContext} + * + * @param methodName Method name to be invoked. + * @param callType Call type to be used. + */ + private ActorMethodContext(String methodName, ActorCallType callType) { + this.methodName = methodName; + this.callType = callType; + } + + /** + * Gets the name of the method invoked by actor runtime. + * + * @return The method name. + */ + public String getMethodName() { + return this.methodName; + } + + /** + * Gets the call type to be used. + * + * @return Call type. + */ + public ActorCallType getCallType() { + return this.callType; + } + + /** + * Creates a context to invoke an Actor's method. + * + * @param methodName THe method to be invoked. + * @return Context of the method call as {@link ActorMethodContext} + */ + static ActorMethodContext CreateForActor(String methodName) { + return new ActorMethodContext(methodName, ActorCallType.ACTOR_INTERFACE_METHOD); + } + + /** + * Creates a context to invoke an Actor's timer. + * + * @param methodName THe method to be invoked. + * @return Context of the method call as {@link ActorMethodContext} + */ + static ActorMethodContext CreateForTimer(String methodName) { + return new ActorMethodContext(methodName, ActorCallType.TIMER_METHOD); + } + + /** + * Creates a context to invoke an Actor's reminder. + * + * @param methodName THe method to be invoked. + * @return Context of the method call as {@link ActorMethodContext} + */ + static ActorMethodContext CreateForReminder(String methodName) { + return new ActorMethodContext(methodName, ActorCallType.REMINDER_METHOD); + } +} diff --git a/sdk/src/main/java/io/dapr/actors/runtime/ActorRuntime.java b/sdk/src/main/java/io/dapr/actors/runtime/ActorRuntime.java index 6574cb8658..be4deb584a 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/ActorRuntime.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/ActorRuntime.java @@ -2,185 +2,184 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors.runtime; +import io.dapr.actors.*; import java.util.Collection; import java.util.Collections; import java.util.HashMap; -import java.util.Set; import java.util.function.Function; -import io.dapr.actors.*; - /** - * Contains methods to register actor types. Registering the types allows the runtime to create instances of the actor. + * Contains methods to register actor types. Registering the types allows the + * runtime to create instances of the actor. */ public class ActorRuntime { - /** - * Gets an instance to the ActorRuntime. There is only 1. - */ - private static volatile ActorRuntime instance; - - /** - * A client used to communicate from the actor to the Dapr runtime. - */ - private static AppToDaprAsyncClient appToDaprAsyncClient; - - /** - * A trace type used when logging. - */ - private static final String TraceType = "ActorRuntime"; - - /** - * Map of ActorType --> ActorManager. - */ - private final HashMap actorManagers; - - /** - * The default constructor. This should not be called directly. - * @throws IllegalStateException - */ - private ActorRuntime() throws IllegalStateException{ - if (instance != null) { - throw new IllegalStateException("ActorRuntime should only be constructed once"); - } - this.actorManagers = new HashMap(); - appToDaprAsyncClient = new AppToDaprClientBuilder().buildAsyncClient(); + /** + * Gets an instance to the ActorRuntime. There is only 1. + */ + private static volatile ActorRuntime instance; + + /** + * A client used to communicate from the actor to the Dapr runtime. + */ + private static AppToDaprAsyncClient appToDaprAsyncClient; + + /** + * A trace type used when logging. + */ + private static final String TraceType = "ActorRuntime"; + + /** + * Map of ActorType --> ActorManager. + */ + private final HashMap actorManagers; + + /** + * The default constructor. This should not be called directly. + * + * @throws IllegalStateException + */ + private ActorRuntime() throws IllegalStateException { + if (instance != null) { + throw new IllegalStateException("ActorRuntime should only be constructed once"); } - /** - * Returns an ActorRuntime object. - * @return An ActorRuntime object. - */ - public static ActorRuntime getInstance() { + this.actorManagers = new HashMap(); + appToDaprAsyncClient = new AppToDaprClientBuilder().buildAsyncClient(); + } + + /** + * Returns an ActorRuntime object. + * + * @return An ActorRuntime object. + */ + public static ActorRuntime getInstance() { + if (instance == null) { + synchronized (ActorRuntime.class) { if (instance == null) { - synchronized (ActorRuntime.class) { - if (instance == null) { - instance = new ActorRuntime(); - } - } - } - - return instance; - } - - /** - * - * @return Actor type names registered with the runtime. - */ - public Collection getRegisteredActorTypes() { - return Collections.unmodifiableCollection(this.actorManagers.keySet()); - } - - /** - * Registers an actor with the runtime. - * @param clazz The type of actor. - */ - public void RegisterActor(Class clazz) { - RegisterActor(clazz, null); - } - - /** - * Registers an actor with the runtime. - * @param clazz The type of actor. - * @param actorServiceFactory An optional delegate to create actor service. This can be used for dependency injection into actors. - */ - public void RegisterActor(Class clazz, Function actorServiceFactory) - { - ActorTypeInformation actorTypeInfo = ActorTypeInformation.create(clazz); - - ActorService actorService; - if (actorServiceFactory != null) - { - actorService = actorServiceFactory.apply(actorTypeInfo); - } - else - { - actorService = new ActorService(actorTypeInfo); - } - - // Create ActorManagers, override existing entry if registered again. - synchronized (this.actorManagers) { - this.actorManagers.put(actorTypeInfo.getName(), new ActorManager(actorService)); + instance = new ActorRuntime(); } + } } - /** - * Activates an actor for an actor type with given actor id. - * @param actorTypeName Actor type name to activate the actor for. - * @param actorId Actor id for the actor to be activated. - */ - static void Activate(String actorTypeName, String actorId) - { - // uncomment when ActorManager implemented - // return instance.GetActorManager(actorTypeName).ActivateActor(new ActorId(actorId)); + return instance; + } + + /** + * + * @return Actor type names registered with the runtime. + */ + public Collection getRegisteredActorTypes() { + return Collections.unmodifiableCollection(this.actorManagers.keySet()); + } + + /** + * Registers an actor with the runtime. + * + * @param clazz The type of actor. + */ + public void RegisterActor(Class clazz) { + RegisterActor(clazz, null); + } + + /** + * Registers an actor with the runtime. + * + * @param clazz The type of actor. + * @param actorServiceFactory An optional delegate to create actor service. + * This can be used for dependency injection into actors. + */ + public void RegisterActor(Class clazz, Function actorServiceFactory) { + ActorTypeInformation actorTypeInfo = ActorTypeInformation.create(clazz); + + ActorService actorService; + if (actorServiceFactory != null) { + actorService = actorServiceFactory.apply(actorTypeInfo); + } else { + actorService = new ActorService(actorTypeInfo); } - /** - * Deactivates an actor for an actor type with given actor id. - * @param actorTypeName Actor type name to deactivate the actor for. - * @param actorId Actor id for the actor to be deactivated. - */ - static void Deactivate(String actorTypeName, String actorId) - { - // uncomment when ActorManager implemented - // return instance.GetActorManager(actorTypeName).DeactivateActor(new ActorId(actorId)); + // Create ActorManagers, override existing entry if registered again. + synchronized (this.actorManagers) { + this.actorManagers.put(actorTypeInfo.getName(), new ActorManager(actorService)); } - - /** - * Invokes the specified method for the actor, this is mainly used for cross language invocation. - * @param actorTypeName Actor type name to invoke the method for. - * @param actorId Actor id for the actor for which method will be invoked. - * @param actorMethodName Method name on actor type which will be invoked. - * @param requestBodyStream Payload for the actor method. - * @param responseBodyStream Response for the actor method. - * @return - */ - static void Dispatch(String actorTypeName, String actorId, String actorMethodName, byte[] requestBodyStream, byte[] responseBodyStream) - { - // uncomment when ActorManager implemented - // return instance.GetActorManager(actorTypeName).Dispatch(new ActorId(actorId), actorMethodName, requestBodyStream, responseBodyStream); + } + + /** + * Activates an actor for an actor type with given actor id. + * + * @param actorTypeName Actor type name to activate the actor for. + * @param actorId Actor id for the actor to be activated. + */ + static void Activate(String actorTypeName, String actorId) { + // uncomment when ActorManager implemented + // return instance.GetActorManager(actorTypeName).ActivateActor(new ActorId(actorId)); + } + + /** + * Deactivates an actor for an actor type with given actor id. + * + * @param actorTypeName Actor type name to deactivate the actor for. + * @param actorId Actor id for the actor to be deactivated. + */ + static void Deactivate(String actorTypeName, String actorId) { + // uncomment when ActorManager implemented + // return instance.GetActorManager(actorTypeName).DeactivateActor(new ActorId(actorId)); + } + + /** + * Invokes the specified method for the actor, this is mainly used for cross + * language invocation. + * + * @param actorTypeName Actor type name to invoke the method for. + * @param actorId Actor id for the actor for which method will be invoked. + * @param actorMethodName Method name on actor type which will be invoked. + * @param requestBodyStream Payload for the actor method. + * @param responseBodyStream Response for the actor method. + * @return + */ + static void Dispatch(String actorTypeName, String actorId, String actorMethodName, byte[] requestBodyStream, byte[] responseBodyStream) { + // uncomment when ActorManager implemented + // return instance.GetActorManager(actorTypeName).Dispatch(new ActorId(actorId), actorMethodName, requestBodyStream, responseBodyStream); + } + + /** + * Fires a reminder for the Actor. + * + * @param actorTypeName Actor type name to invoke the method for. + * @param actorId Actor id for the actor for which method will be invoked. + * @param reminderName The name of reminder provided during registration. + * @param requestBodyStream Payload for the actor method + */ + static void FireReminder(String actorTypeName, String actorId, String reminderName, byte[] requestBodyStream) { + // uncomment when ActorManager implemented + // return instance.GetActorManager(actorTypeName).FireReminder(new ActorId(actorId), reminderName, requestBodyStream); + } + + /** + * Fires a timer for the Actor. + * + * @param actorTypeName Actor type name to invoke the method for. + * @param actorId Actor id for the actor for which method will be invoked. + * @param timerName The name of timer provided during registration. + */ + static void FireTimer(String actorTypeName, String actorId, String timerName) { + // uncomment when ActorManager implemented + // return instance.GetActorManager(actorTypeName).FireTimerAsync(new ActorId(actorId), timerName); + } + + private ActorManager GetActorManager(String actorTypeName) throws IllegalStateException { + ActorManager actorManager = this.actorManagers.get(actorTypeName); + + if (actorManager == null) { + String errorMsg = String.format("Actor type %s is not registered with Actor runtime.", actorTypeName); + + ActorTrace.WriteError(errorMsg); + throw new IllegalStateException(errorMsg); } - /** - * Fires a reminder for the Actor. - * @param actorTypeName Actor type name to invoke the method for. - * @param actorId Actor id for the actor for which method will be invoked. - * @param reminderName The name of reminder provided during registration. - * @param requestBodyStream Payload for the actor method - */ - static void FireReminder(String actorTypeName, String actorId, String reminderName, byte[] requestBodyStream) - { - // uncomment when ActorManager implemented - // return instance.GetActorManager(actorTypeName).FireReminder(new ActorId(actorId), reminderName, requestBodyStream); - } - - /** - * Fires a timer for the Actor. - * @param actorTypeName Actor type name to invoke the method for. - * @param actorId Actor id for the actor for which method will be invoked. - * @param timerName The name of timer provided during registration. - */ - static void FireTimer(String actorTypeName, String actorId, String timerName) - { - // uncomment when ActorManager implemented - // return instance.GetActorManager(actorTypeName).FireTimerAsync(new ActorId(actorId), timerName); - } - - private ActorManager GetActorManager(String actorTypeName) throws IllegalStateException - { - ActorManager actorManager = this.actorManagers.get(actorTypeName); - - if (actorManager == null) - { - String errorMsg = String.format("Actor type %s is not registered with Actor runtime.", actorTypeName); - - ActorTrace.WriteError(errorMsg); - throw new IllegalStateException(errorMsg); - } - - return actorManager; - } + return actorManager; + } } \ No newline at end of file diff --git a/sdk/src/main/java/io/dapr/actors/runtime/ActorService.java b/sdk/src/main/java/io/dapr/actors/runtime/ActorService.java index 110f6fc248..385ff32884 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/ActorService.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/ActorService.java @@ -2,7 +2,8 @@ // stub public class ActorService { - public ActorService(ActorTypeInformation actorTypeInformation) { - } + public ActorService(ActorTypeInformation actorTypeInformation) { + + } } diff --git a/sdk/src/main/java/io/dapr/actors/runtime/ActorStateProviderSerializer.java b/sdk/src/main/java/io/dapr/actors/runtime/ActorStateProviderSerializer.java index a559458501..3a52c45fc8 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/ActorStateProviderSerializer.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/ActorStateProviderSerializer.java @@ -1,44 +1,44 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ - -package io.dapr.actors.runtime; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; - -/** - * Serializes and deserializes an object. - */ -class ActorStateProviderSerializer { - - /** - * Shared Json serializer/deserializer as per Jackson's documentation. - */ - private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - - /** - * Serializes a given state object into byte array. - * @param state State object to be serialized. - * @return Array of bytes[] with the serialized content. - * @throws IOException - */ - byte[] serialize(Object state) throws IOException { - return OBJECT_MAPPER.writeValueAsBytes(state); - } - - /** - * Deserializes the byte array into the original object. - * @param buffer Array of bytes to be parsed. - * @param clazz Type of the object being deserialized. - * @param Generic type of the object being deserialized. - * @return Object of type T. - * @throws IOException - */ - T deserialize(byte[] buffer, Class clazz) throws IOException { - return OBJECT_MAPPER.readValue(buffer, clazz); - } - -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors.runtime; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; + +/** + * Serializes and deserializes an object. + */ +class ActorStateProviderSerializer { + + /** + * Shared Json serializer/deserializer as per Jackson's documentation. + */ + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + /** + * Serializes a given state object into byte array. + * + * @param state State object to be serialized. + * @return Array of bytes[] with the serialized content. + * @throws IOException + */ + byte[] serialize(Object state) throws IOException { + return OBJECT_MAPPER.writeValueAsBytes(state); + } + + /** + * Deserializes the byte array into the original object. + * + * @param buffer Array of bytes to be parsed. + * @param clazz Type of the object being deserialized. + * @param Generic type of the object being deserialized. + * @return Object of type T. + * @throws IOException + */ + T deserialize(byte[] buffer, Class clazz) throws IOException { + return OBJECT_MAPPER.readValue(buffer, clazz); + } + +} diff --git a/sdk/src/main/java/io/dapr/actors/runtime/ActorType.java b/sdk/src/main/java/io/dapr/actors/runtime/ActorType.java index fcedd667f7..72d5f2713d 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/ActorType.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/ActorType.java @@ -1,20 +1,19 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ - -package io.dapr.actors.runtime; - -import java.lang.annotation.*; - -/** - * Annotation to override default behavior of Actor class. - */ -@Documented -@Target(ElementType.TYPE_USE) -@Retention(RetentionPolicy.RUNTIME) -public @interface ActorType { - - String Name(); - -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors.runtime; + +import java.lang.annotation.*; + +/** + * Annotation to override default behavior of Actor class. + */ +@Documented +@Target(ElementType.TYPE_USE) +@Retention(RetentionPolicy.RUNTIME) +public @interface ActorType { + + String Name(); + +} diff --git a/sdk/src/main/java/io/dapr/actors/runtime/ActorTypeInformation.java b/sdk/src/main/java/io/dapr/actors/runtime/ActorTypeInformation.java index 5c21557dc4..97564a5cc7 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/ActorTypeInformation.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/ActorTypeInformation.java @@ -1,159 +1,165 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ -package io.dapr.actors.runtime; - -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; - -/** - * Contains the information about the class implementing an actor. - */ -final class ActorTypeInformation { - - /** - * Actor type's name. - */ - private final String name; - - /** - * Actor's implementation class. - */ - private final Class implementationClass; - - /** - * Actor's immediate interfaces. - */ - private final Collection interfaces; - - /** - * Whether Actor type is abstract. - */ - private final boolean abstractClass; - - /** - * Whether Actor type is remindable. - */ - private final boolean remindable; - - /** - * Instantiates a new {@link ActorTypeInformation} - * @param name Actor type's name. - * @param implementationClass Actor's implementation class. - * @param interfaces Actor's immediate interfaces. - * @param abstractClass Whether Actor type is abstract. - * @param remindable Whether Actor type is remindable. - */ - private ActorTypeInformation(String name, - Class implementationClass, - Collection interfaces, - boolean abstractClass, - boolean remindable) { - this.name = name; - this.implementationClass = implementationClass; - this.interfaces = interfaces; - this.abstractClass = abstractClass; - this.remindable = remindable; - } - - /** - * Returns the name of this ActorType. - * @return ActorType's name. - */ - public String getName() { - return this.name; - } - - /** - * Gets the type of the class implementing the actor. - * - * @return The {@link Class} of implementing the actor. - */ - public Class getImplementationClass() { - return this.implementationClass; - } - - /** - * Gets the actor interfaces which derive from {@link Actor} and implemented by actor class. - * - * @return Collection of actor interfaces. - */ - public Collection getInterfaces() { - return Collections.unmodifiableCollection(this.interfaces); - } - - /** - * Gets a value indicating whether the class implementing actor is abstract. - * - * @return true if the class implementing actor is abstract, otherwise false. - */ - public boolean isAbstractClass() { - return this.abstractClass; - } - - /** - * Gets a value indicating whether the actor class implements {@link Remindable}. - * - * @return true if the actor class implements {@link Remindable}. - */ - public boolean isRemindable() { - return this.remindable; - } - - /** - * Creates the {@link ActorTypeInformation} from given Class. - * - * @param actorClass The type of class implementing the actor to create ActorTypeInformation for. - * @return ActorTypeInformation if successfully created for actorType or null. - */ - public static ActorTypeInformation tryCreate(Class actorClass) { - try { - return create(actorClass); - } catch (IllegalArgumentException e) { - return null; - } - } - - /** - * Creates an {@link #ActorTypeInformation} from actorType. - * - * @param actorClass The class implementing the actor to create ActorTypeInformation for. - * @return {@link #ActorTypeInformation} created from actorType. - */ - public static ActorTypeInformation create(Class actorClass) { - if (!ActorTypeUtilities.isActor(actorClass)) { - throw new IllegalArgumentException( - String.format( - "The type '%s' is not an Actor. An actor type must derive from '%s'.", - actorClass == null ? "" : actorClass.getCanonicalName(), - Actor.class.getCanonicalName())); - } - - // get all actor interfaces - Class[] actorInterfaces = actorClass.getInterfaces(); - - boolean isAbstract = Modifier.isAbstract(actorClass.getModifiers()); - // ensure that the if the actor type is not abstract it implements at least one actor interface - if ((actorInterfaces.length == 0) && !isAbstract) { - throw new IllegalArgumentException( - String.format( - "The actor type '%s' does not implement any actor interfaces or one of the " + - "interfaces implemented is not an actor interface. " + - "All interfaces(including its parent interface) implemented by actor type must " + - "be actor interface. An actor interface is the one that ultimately derives " + - "from '%s' type.", - actorClass == null ? "" : actorClass.getCanonicalName(), - Actor.class.getCanonicalName())); - } - - boolean isRemindable = ActorTypeUtilities.isRemindableActor(actorClass); - ActorType actorTypeAnnotation = (ActorType) actorClass.getAnnotation(ActorType.class); - String typeName = actorTypeAnnotation != null ? actorTypeAnnotation.Name() : actorClass.getSimpleName(); - - return new ActorTypeInformation(typeName, actorClass, Arrays.asList(actorInterfaces), isAbstract, isRemindable); - } - -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors.runtime; + +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; + +/** + * Contains the information about the class implementing an actor. + */ +final class ActorTypeInformation { + + /** + * Actor type's name. + */ + private final String name; + + /** + * Actor's implementation class. + */ + private final Class implementationClass; + + /** + * Actor's immediate interfaces. + */ + private final Collection interfaces; + + /** + * Whether Actor type is abstract. + */ + private final boolean abstractClass; + + /** + * Whether Actor type is remindable. + */ + private final boolean remindable; + + /** + * Instantiates a new {@link ActorTypeInformation} + * + * @param name Actor type's name. + * @param implementationClass Actor's implementation class. + * @param interfaces Actor's immediate interfaces. + * @param abstractClass Whether Actor type is abstract. + * @param remindable Whether Actor type is remindable. + */ + private ActorTypeInformation(String name, + Class implementationClass, + Collection interfaces, + boolean abstractClass, + boolean remindable) { + this.name = name; + this.implementationClass = implementationClass; + this.interfaces = interfaces; + this.abstractClass = abstractClass; + this.remindable = remindable; + } + + /** + * Returns the name of this ActorType. + * + * @return ActorType's name. + */ + public String getName() { + return this.name; + } + + /** + * Gets the type of the class implementing the actor. + * + * @return The {@link Class} of implementing the actor. + */ + public Class getImplementationClass() { + return this.implementationClass; + } + + /** + * Gets the actor interfaces which derive from {@link Actor} and implemented + * by actor class. + * + * @return Collection of actor interfaces. + */ + public Collection getInterfaces() { + return Collections.unmodifiableCollection(this.interfaces); + } + + /** + * Gets a value indicating whether the class implementing actor is abstract. + * + * @return true if the class implementing actor is abstract, otherwise false. + */ + public boolean isAbstractClass() { + return this.abstractClass; + } + + /** + * Gets a value indicating whether the actor class implements + * {@link Remindable}. + * + * @return true if the actor class implements {@link Remindable}. + */ + public boolean isRemindable() { + return this.remindable; + } + + /** + * Creates the {@link ActorTypeInformation} from given Class. + * + * @param actorClass The type of class implementing the actor to create + * ActorTypeInformation for. + * @return ActorTypeInformation if successfully created for actorType or null. + */ + public static ActorTypeInformation tryCreate(Class actorClass) { + try { + return create(actorClass); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Creates an {@link #ActorTypeInformation} from actorType. + * + * @param actorClass The class implementing the actor to create + * ActorTypeInformation for. + * @return {@link #ActorTypeInformation} created from actorType. + */ + public static ActorTypeInformation create(Class actorClass) { + if (!ActorTypeUtilities.isActor(actorClass)) { + throw new IllegalArgumentException( + String.format( + "The type '%s' is not an Actor. An actor type must derive from '%s'.", + actorClass == null ? "" : actorClass.getCanonicalName(), + Actor.class.getCanonicalName())); + } + + // get all actor interfaces + Class[] actorInterfaces = actorClass.getInterfaces(); + + boolean isAbstract = Modifier.isAbstract(actorClass.getModifiers()); + // ensure that the if the actor type is not abstract it implements at least one actor interface + if ((actorInterfaces.length == 0) && !isAbstract) { + throw new IllegalArgumentException( + String.format( + "The actor type '%s' does not implement any actor interfaces or one of the " + + "interfaces implemented is not an actor interface. " + + "All interfaces(including its parent interface) implemented by actor type must " + + "be actor interface. An actor interface is the one that ultimately derives " + + "from '%s' type.", + actorClass == null ? "" : actorClass.getCanonicalName(), + Actor.class.getCanonicalName())); + } + + boolean isRemindable = ActorTypeUtilities.isRemindableActor(actorClass); + ActorType actorTypeAnnotation = (ActorType) actorClass.getAnnotation(ActorType.class); + String typeName = actorTypeAnnotation != null ? actorTypeAnnotation.Name() : actorClass.getSimpleName(); + + return new ActorTypeInformation(typeName, actorClass, Arrays.asList(actorInterfaces), isAbstract, isRemindable); + } + +} diff --git a/sdk/src/main/java/io/dapr/actors/runtime/ActorTypeUtilities.java b/sdk/src/main/java/io/dapr/actors/runtime/ActorTypeUtilities.java index 70ab9f3d55..67384508ce 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/ActorTypeUtilities.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/ActorTypeUtilities.java @@ -1,87 +1,91 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ - -package io.dapr.actors.runtime; - -import java.util.Arrays; - -/** - * Utility class to extract information on Actor type. - */ -final class ActorTypeUtilities { - - /** - * Gets all interfaces that extend Actor. - * @param clazz Actor class. - * @return Array of Actor interfaces. - */ - public static Class[] getActorInterfaces(Class clazz) { - if (clazz == null) { - return new Class[0]; - } - - - return Arrays.stream(clazz.getInterfaces()) - .filter(t -> Actor.class.isAssignableFrom(t)) - .filter(t -> getNonActorParentClass(t) == null) - .toArray(Class[]::new); - } - - /** - * Determines if given class is an Actor interface. - * @param clazz Actor interface candidate. - * @return Whether this is an Actor interface. - */ - public static boolean isActorInterface(Class clazz) { - return (clazz != null) && clazz.isInterface() && (getNonActorParentClass(clazz) == null); - } - - /** - * Determines whether this is an Actor class. - * @param clazz Actor class candidate. - * @return Whether this is an Actor class. - */ - public static boolean isActor(Class clazz) { - if (clazz == null) { - return false; - } - - return AbstractActor.class.isAssignableFrom(clazz); - } - - /** - * Determines whether this is an remindable Actor. - * @param clazz Actor class. - * @return Whether this is an remindable Actor. - */ - public static boolean isRemindableActor(Class clazz) { - return (clazz != null) && isActor(clazz) && (Arrays.stream(clazz.getInterfaces()).filter(t -> t.equals(Remindable.class)).count() > 0); - } - - /** - * Returns the parent class if it is not the {@link AbstractActor} parent class. - * @param clazz Actor class. - * @return Parent class or null if it is {@link AbstractActor}. - */ - public static Class getNonActorParentClass(Class clazz) { - if (clazz == null) { - return null; - } - - Class[] items = Arrays.stream(clazz.getInterfaces()).filter(t -> !t.equals(Actor.class)).toArray(Class[]::new); - if (items.length == 0) { - return clazz; - } - - for (Class c : items) { - Class nonActorParent = getNonActorParentClass(c); - if (nonActorParent != null) { - return nonActorParent; - } - } - - return null; - } -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors.runtime; + +import java.util.Arrays; + +/** + * Utility class to extract information on Actor type. + */ +final class ActorTypeUtilities { + + /** + * Gets all interfaces that extend Actor. + * + * @param clazz Actor class. + * @return Array of Actor interfaces. + */ + public static Class[] getActorInterfaces(Class clazz) { + if (clazz == null) { + return new Class[0]; + } + + return Arrays.stream(clazz.getInterfaces()) + .filter(t -> Actor.class.isAssignableFrom(t)) + .filter(t -> getNonActorParentClass(t) == null) + .toArray(Class[]::new); + } + + /** + * Determines if given class is an Actor interface. + * + * @param clazz Actor interface candidate. + * @return Whether this is an Actor interface. + */ + public static boolean isActorInterface(Class clazz) { + return (clazz != null) && clazz.isInterface() && (getNonActorParentClass(clazz) == null); + } + + /** + * Determines whether this is an Actor class. + * + * @param clazz Actor class candidate. + * @return Whether this is an Actor class. + */ + public static boolean isActor(Class clazz) { + if (clazz == null) { + return false; + } + + return AbstractActor.class.isAssignableFrom(clazz); + } + + /** + * Determines whether this is an remindable Actor. + * + * @param clazz Actor class. + * @return Whether this is an remindable Actor. + */ + public static boolean isRemindableActor(Class clazz) { + return (clazz != null) && isActor(clazz) && (Arrays.stream(clazz.getInterfaces()).filter(t -> t.equals(Remindable.class)).count() > 0); + } + + /** + * Returns the parent class if it is not the {@link AbstractActor} parent + * class. + * + * @param clazz Actor class. + * @return Parent class or null if it is {@link AbstractActor}. + */ + public static Class getNonActorParentClass(Class clazz) { + if (clazz == null) { + return null; + } + + Class[] items = Arrays.stream(clazz.getInterfaces()).filter(t -> !t.equals(Actor.class)).toArray(Class[]::new); + if (items.length == 0) { + return clazz; + } + + for (Class c : items) { + Class nonActorParent = getNonActorParentClass(c); + if (nonActorParent != null) { + return nonActorParent; + } + } + + return null; + } +} diff --git a/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprAsyncClient.java b/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprAsyncClient.java index 66fe3d1757..b31c7beca9 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprAsyncClient.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprAsyncClient.java @@ -2,70 +2,74 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors.runtime; import reactor.core.publisher.Mono; - /** * Interface for interacting from the actor app to the Dapr runtime. */ interface AppToDaprAsyncClient { - /** - * Gets a state from Dapr's Actor. - * @param actorType Type of actor. - * @param actorId Actor Identifier. - * @param keyName State name. - * @return Asynchronous result with current state value. - */ - Mono getState(String actorType, String actorId, String keyName); + /** + * Gets a state from Dapr's Actor. + * + * @param actorType Type of actor. + * @param actorId Actor Identifier. + * @param keyName State name. + * @return Asynchronous result with current state value. + */ + Mono getState(String actorType, String actorId, String keyName); - /** - * Saves state batch to Dapr. - * @param actorType Type of actor. - * @param actorId Actor Identifier. - * @param data State to be saved. - * @return Asynchronous void result. - */ - Mono saveStateTransactionally(String actorType, String actorId, String data); + /** + * Saves state batch to Dapr. + * + * @param actorType Type of actor. + * @param actorId Actor Identifier. + * @param data State to be saved. + * @return Asynchronous void result. + */ + Mono saveStateTransactionally(String actorType, String actorId, String data); - /** - * Register a reminder. - * @param actorType Type of actor. - * @param actorId Actor Identifier. - * @param reminderName Name of reminder to be registered. - * @param data JSON reminder data as per Dapr's spec. - * @return Asynchronous void result. - */ - Mono registerReminder(String actorType, String actorId, String reminderName, String data); + /** + * Register a reminder. + * + * @param actorType Type of actor. + * @param actorId Actor Identifier. + * @param reminderName Name of reminder to be registered. + * @param data JSON reminder data as per Dapr's spec. + * @return Asynchronous void result. + */ + Mono registerReminder(String actorType, String actorId, String reminderName, String data); - /** - * Unregisters a reminder. - * @param actorType Type of actor. - * @param actorId Actor Identifier. - * @param reminderName Name of reminder to be unregistered. - * @return Asynchronous void result. - */ - Mono unregisterReminder(String actorType, String actorId, String reminderName); + /** + * Unregisters a reminder. + * + * @param actorType Type of actor. + * @param actorId Actor Identifier. + * @param reminderName Name of reminder to be unregistered. + * @return Asynchronous void result. + */ + Mono unregisterReminder(String actorType, String actorId, String reminderName); - /** - * Registers a timer. - * @param actorType Type of actor. - * @param actorId Actor Identifier. - * @param timerName Name of timer to be registered. - * @param data JSON reminder data as per Dapr's spec. - * @return Asynchronous void result. - */ - Mono registerTimer(String actorType, String actorId, String timerName, String data); + /** + * Registers a timer. + * + * @param actorType Type of actor. + * @param actorId Actor Identifier. + * @param timerName Name of timer to be registered. + * @param data JSON reminder data as per Dapr's spec. + * @return Asynchronous void result. + */ + Mono registerTimer(String actorType, String actorId, String timerName, String data); - /** - * Unregisters a timer. - * @param actorType Type of actor. - * @param actorId Actor Identifier. - * @param timerName Name of timer to be unregistered. - * @return Asynchronous void result. - */ - Mono unregisterTimerAsync(String actorType, String actorId, String timerName); + /** + * Unregisters a timer. + * + * @param actorType Type of actor. + * @param actorId Actor Identifier. + * @param timerName Name of timer to be unregistered. + * @return Asynchronous void result. + */ + Mono unregisterTimerAsync(String actorType, String actorId, String timerName); } diff --git a/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprClientBuilder.java b/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprClientBuilder.java index 1476057ca3..48bb382c0d 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprClientBuilder.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprClientBuilder.java @@ -2,29 +2,29 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors.runtime; -import okhttp3.OkHttpClient; import io.dapr.actors.*; +import okhttp3.OkHttpClient; /** * Builds an instance of AppToDaprAsyncClient. */ class AppToDaprClientBuilder extends AbstractClientBuilder { - /** - * Default port for Dapr after checking environment variable. - */ - private int port = AppToDaprClientBuilder.GetEnvPortOrDefault(); + /** + * Default port for Dapr after checking environment variable. + */ + private int port = AppToDaprClientBuilder.GetEnvPortOrDefault(); - /** - * Builds an async client. - * @return Builds an async client. - */ - public AppToDaprAsyncClient buildAsyncClient() { - OkHttpClient.Builder builder = new OkHttpClient.Builder(); - // TODO: Expose configurations for OkHttpClient or com.microsoft.rest.RestClient. - return new AppToDaprHttpAsyncClient(this.port, builder.build()); - } + /** + * Builds an async client. + * + * @return Builds an async client. + */ + public AppToDaprAsyncClient buildAsyncClient() { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + // TODO: Expose configurations for OkHttpClient or com.microsoft.rest.RestClient. + return new AppToDaprHttpAsyncClient(this.port, builder.build()); + } } diff --git a/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprHttpAsyncClient.java b/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprHttpAsyncClient.java index 6c4041042b..82259c79db 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprHttpAsyncClient.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/AppToDaprHttpAsyncClient.java @@ -2,82 +2,80 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors.runtime; -import io.dapr.actors.Constants; import io.dapr.actors.AbstractDaprClient; +import io.dapr.actors.Constants; import okhttp3.*; import reactor.core.publisher.Mono; - /** * Http client to call Dapr's API for actors. */ //public class DaprHttpAsyncClient implements DaprAsyncClient { class AppToDaprHttpAsyncClient extends AbstractDaprClient implements AppToDaprAsyncClient { - /** - * Creates a new instance of {@link AppToDaprHttpAsyncClient}. - * @param port Port for calling Dapr. (e.g. 3500) - * @param httpClient RestClient used for all API calls in this new instance. - */ - public AppToDaprHttpAsyncClient(int port, OkHttpClient httpClient) - { - super(port, httpClient); - } + /** + * Creates a new instance of {@link AppToDaprHttpAsyncClient}. + * + * @param port Port for calling Dapr. (e.g. 3500) + * @param httpClient RestClient used for all API calls in this new instance. + */ + public AppToDaprHttpAsyncClient(int port, OkHttpClient httpClient) { + super(port, httpClient); + } - /** - * {@inheritDoc} - */ - @Override - public Mono getState(String actorType, String actorId, String keyName) { - String url = String.format(Constants.ACTOR_STATE_KEY_RELATIVE_URL_FORMAT, actorType, actorId, keyName); - return super.invokeAPI("GET", url, null); - } + /** + * {@inheritDoc} + */ + @Override + public Mono getState(String actorType, String actorId, String keyName) { + String url = String.format(Constants.ACTOR_STATE_KEY_RELATIVE_URL_FORMAT, actorType, actorId, keyName); + return super.invokeAPI("GET", url, null); + } - /** - * {@inheritDoc} - */ - @Override - public Mono saveStateTransactionally(String actorType, String actorId, String data) { - String url = String.format(Constants.ACTOR_STATE_RELATIVE_URL_FORMAT, actorType, actorId); - return super.invokeAPIVoid("PUT", url, data); - } + /** + * {@inheritDoc} + */ + @Override + public Mono saveStateTransactionally(String actorType, String actorId, String data) { + String url = String.format(Constants.ACTOR_STATE_RELATIVE_URL_FORMAT, actorType, actorId); + return super.invokeAPIVoid("PUT", url, data); + } - /** - * {@inheritDoc} - */ - @Override - public Mono registerReminder(String actorType, String actorId, String reminderName, String data) { - String url = String.format(Constants.ACTOR_REMINDER_RELATIVE_URL_FORMAT, actorType, actorId, reminderName); - return super.invokeAPIVoid("PUT", url, data); - } + /** + * {@inheritDoc} + */ + @Override + public Mono registerReminder(String actorType, String actorId, String reminderName, String data) { + String url = String.format(Constants.ACTOR_REMINDER_RELATIVE_URL_FORMAT, actorType, actorId, reminderName); + return super.invokeAPIVoid("PUT", url, data); + } - /** - * {@inheritDoc} - */ - @Override - public Mono unregisterReminder(String actorType, String actorId, String reminderName) { - String url = String.format(Constants.ACTOR_REMINDER_RELATIVE_URL_FORMAT, actorType, actorId, reminderName); - return super.invokeAPIVoid("DELETE", url, null); - } + /** + * {@inheritDoc} + */ + @Override + public Mono unregisterReminder(String actorType, String actorId, String reminderName) { + String url = String.format(Constants.ACTOR_REMINDER_RELATIVE_URL_FORMAT, actorType, actorId, reminderName); + return super.invokeAPIVoid("DELETE", url, null); + } - /** - * {@inheritDoc} - */ - @Override - public Mono registerTimer(String actorType, String actorId, String timerName, String data) { - String url = String.format(Constants.ACTOR_TIMER_RELATIVE_URL_FORMAT, actorType, actorId, timerName); - return super.invokeAPIVoid("PUT", url, data); - } + /** + * {@inheritDoc} + */ + @Override + public Mono registerTimer(String actorType, String actorId, String timerName, String data) { + String url = String.format(Constants.ACTOR_TIMER_RELATIVE_URL_FORMAT, actorType, actorId, timerName); + return super.invokeAPIVoid("PUT", url, data); + } - /** - * {@inheritDoc} - */ - @Override - public Mono unregisterTimerAsync(String actorType, String actorId, String timerName) { - String url = String.format(Constants.ACTOR_TIMER_RELATIVE_URL_FORMAT, actorType, actorId, timerName); - return super.invokeAPIVoid("DELETE", url, null); - } + /** + * {@inheritDoc} + */ + @Override + public Mono unregisterTimerAsync(String actorType, String actorId, String timerName) { + String url = String.format(Constants.ACTOR_TIMER_RELATIVE_URL_FORMAT, actorType, actorId, timerName); + return super.invokeAPIVoid("DELETE", url, null); + } } diff --git a/sdk/src/main/java/io/dapr/actors/runtime/Remindable.java b/sdk/src/main/java/io/dapr/actors/runtime/Remindable.java index 05adc464e6..bbdada8175 100644 --- a/sdk/src/main/java/io/dapr/actors/runtime/Remindable.java +++ b/sdk/src/main/java/io/dapr/actors/runtime/Remindable.java @@ -1,12 +1,11 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - */ - -package io.dapr.actors.runtime; - -/** - * TODO - */ -public interface Remindable { -} +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + */ +package io.dapr.actors.runtime; + +/** + * TODO + */ +public interface Remindable { +} diff --git a/sdk/src/test/java/io/dapr/actors/ActorIdTest.java b/sdk/src/test/java/io/dapr/actors/ActorIdTest.java index 6d37a3d20e..1c68755614 100644 --- a/sdk/src/test/java/io/dapr/actors/ActorIdTest.java +++ b/sdk/src/test/java/io/dapr/actors/ActorIdTest.java @@ -2,12 +2,9 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors; import java.util.*; -import java.lang.String; - import org.junit.Assert; import org.junit.Test; @@ -16,81 +13,82 @@ */ public class ActorIdTest { - @Test(expected = IllegalArgumentException.class) - public void initializeNewActorIdObjectWithNullId() { - ActorId actorId = new ActorId(null); - } + @Test(expected = IllegalArgumentException.class) + public void initializeNewActorIdObjectWithNullId() { + ActorId actorId = new ActorId(null); + } - @Test - public void getId() { - String id = "123"; - ActorId actorId = new ActorId(id); - Assert.assertEquals(id, actorId.getStringId()); - } + @Test + public void getId() { + String id = "123"; + ActorId actorId = new ActorId(id); + Assert.assertEquals(id, actorId.getStringId()); + } - @Test - public void verifyToString() { - String id = "123"; - ActorId actorId = new ActorId(id); - Assert.assertEquals(id, actorId.toString()); - } + @Test + public void verifyToString() { + String id = "123"; + ActorId actorId = new ActorId(id); + Assert.assertEquals(id, actorId.toString()); + } - @Test - public void verifyEqualsByObject() { - List values = createEqualsTestValues(); - for (Wrapper w : values) { - Assert.assertEquals(w.expectedResult, w.item1.equals(w.item2)); - } + @Test + public void verifyEqualsByObject() { + List values = createEqualsTestValues(); + for (Wrapper w : values) { + Assert.assertEquals(w.expectedResult, w.item1.equals(w.item2)); } + } - @Test - public void verifyEqualsByActorId() { - List values = createEqualsTestValues(); - for (Wrapper w : values) { - ActorId a1 = (ActorId) w.item1; - ActorId a2 = (ActorId) w.item2; - Assert.assertEquals(w.expectedResult, a1.equals(a2)); - } + @Test + public void verifyEqualsByActorId() { + List values = createEqualsTestValues(); + for (Wrapper w : values) { + ActorId a1 = (ActorId) w.item1; + ActorId a2 = (ActorId) w.item2; + Assert.assertEquals(w.expectedResult, a1.equals(a2)); } + } - @Test - public void verifyCompareTo() { - List values = createComparesToTestValues(); - for (Wrapper w : values) { - ActorId a1 = (ActorId) w.item1; - ActorId a2 = (ActorId) w.item2; - Assert.assertEquals(w.expectedResult, a1.compareTo(a2)); - } + @Test + public void verifyCompareTo() { + List values = createComparesToTestValues(); + for (Wrapper w : values) { + ActorId a1 = (ActorId) w.item1; + ActorId a2 = (ActorId) w.item2; + Assert.assertEquals(w.expectedResult, a1.compareTo(a2)); } + } - private List createEqualsTestValues() { - List list = new ArrayList(); - list.add(new Wrapper(new ActorId("1"), null, false)); - list.add(new Wrapper(new ActorId("1"), new ActorId("1"), true)); - list.add(new Wrapper(new ActorId("1"), new ActorId("2"), false)); + private List createEqualsTestValues() { + List list = new ArrayList(); + list.add(new Wrapper(new ActorId("1"), null, false)); + list.add(new Wrapper(new ActorId("1"), new ActorId("1"), true)); + list.add(new Wrapper(new ActorId("1"), new ActorId("2"), false)); - return list; - } + return list; + } - private List createComparesToTestValues() { - List list = new ArrayList(); - list.add(new Wrapper(new ActorId("1"), null, 1)); - list.add(new Wrapper(new ActorId("1"), new ActorId("1"), 0)); - list.add(new Wrapper(new ActorId("1"), new ActorId("2"), -1)); - list.add(new Wrapper(new ActorId("2"), new ActorId("1"), 1)); + private List createComparesToTestValues() { + List list = new ArrayList(); + list.add(new Wrapper(new ActorId("1"), null, 1)); + list.add(new Wrapper(new ActorId("1"), new ActorId("1"), 0)); + list.add(new Wrapper(new ActorId("1"), new ActorId("2"), -1)); + list.add(new Wrapper(new ActorId("2"), new ActorId("1"), 1)); - return list; - } - - class Wrapper { - public Object item1; - public Object item2; - public T expectedResult; + return list; + } + + class Wrapper { + + public Object item1; + public Object item2; + public T expectedResult; - public Wrapper(Object i, Object j, T e) { - this.item1 = i; - this.item2 = j; - this.expectedResult = e; - } + public Wrapper(Object i, Object j, T e) { + this.item1 = i; + this.item2 = j; + this.expectedResult = e; } + } } diff --git a/sdk/src/test/java/io/dapr/actors/client/DaprHttpAsyncClientIT.java b/sdk/src/test/java/io/dapr/actors/client/DaprHttpAsyncClientIT.java index 3096f13a89..67d945e071 100644 --- a/sdk/src/test/java/io/dapr/actors/client/DaprHttpAsyncClientIT.java +++ b/sdk/src/test/java/io/dapr/actors/client/DaprHttpAsyncClientIT.java @@ -2,7 +2,6 @@ * Copyright (c) Microsoft Corporation. * Licensed under the MIT License. */ - package io.dapr.actors.client; import io.dapr.actors.*; @@ -16,28 +15,29 @@ */ public class DaprHttpAsyncClientIT { - /** - * Checks if the error is correctly parsed when trying to invoke a function on an unknown actor type. - */ - @Test(expected = RuntimeException.class) - public void invokeUnknownActor() { - ActorProxyAsyncClient daprAsyncClient = new ActorProxyClientBuilder().buildAsyncClient(); - daprAsyncClient - .invokeActorMethod("ActorThatDoesNotExist", "100", "GetData", null) - .doOnError(x -> { - Assert.assertTrue(x instanceof RuntimeException); - RuntimeException runtimeException = (RuntimeException)x; + /** + * Checks if the error is correctly parsed when trying to invoke a function on + * an unknown actor type. + */ + @Test(expected = RuntimeException.class) + public void invokeUnknownActor() { + ActorProxyAsyncClient daprAsyncClient = new ActorProxyClientBuilder().buildAsyncClient(); + daprAsyncClient + .invokeActorMethod("ActorThatDoesNotExist", "100", "GetData", null) + .doOnError(x -> { + Assert.assertTrue(x instanceof RuntimeException); + RuntimeException runtimeException = (RuntimeException) x; - Throwable cause = runtimeException.getCause(); - Assert.assertTrue(cause instanceof DaprException); - DaprException daprException = (DaprException)cause; + Throwable cause = runtimeException.getCause(); + Assert.assertTrue(cause instanceof DaprException); + DaprException daprException = (DaprException) cause; - Assert.assertNotNull(daprException); - Assert.assertEquals("ERR_INVOKE_ACTOR", daprException.getErrorCode()); - Assert.assertNotNull(daprException.getMessage()); - Assert.assertFalse(daprException.getMessage().isEmpty()); - }) - .doOnSuccess(x -> Assert.fail("This call should fail.")) - .block(); - } + Assert.assertNotNull(daprException); + Assert.assertEquals("ERR_INVOKE_ACTOR", daprException.getErrorCode()); + Assert.assertNotNull(daprException.getMessage()); + Assert.assertFalse(daprException.getMessage().isEmpty()); + }) + .doOnSuccess(x -> Assert.fail("This call should fail.")) + .block(); + } }