More reformatting to 2 spaces indentation. (#50)

This commit is contained in:
Artur Souza 2019-12-16 16:14:17 -08:00 committed by GitHub
parent 78fec8f840
commit 6733fcdda8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 628 additions and 619 deletions

View File

@ -9,8 +9,8 @@ package io.dapr.examples.actors.http;
* Client that will use Actor.
*/
public class ActorClient {
// TODO.
// TODO.
public static void main(String[] args) throws Exception {
}
public static void main(String[] args) throws Exception {
}
}

View File

@ -9,5 +9,5 @@ package io.dapr.examples.actors.http;
* Example of implementation of an Actor.
*/
public interface DemoActor {
// TODO.
// TODO.
}

View File

@ -9,5 +9,5 @@ package io.dapr.examples.actors.http;
* Implementation of the DemoActor for the server side.
*/
public class DemoActorImpl {
// TODO.
// TODO.
}

View File

@ -10,7 +10,7 @@ package io.dapr.examples.actors.http;
*/
public class DemoActorService {
public static void main(String[] args) throws Exception {
// TODO
}
public static void main(String[] args) throws Exception {
// TODO
}
}

View File

@ -23,105 +23,108 @@ import static io.dapr.examples.DaprExamplesProtos.SayResponse;
/**
* 1. Build and install jars:
* mvn clean install
* mvn clean install
* 2. Send messages to the server:
* dapr run --protocol grpc --grpc-port 50001 -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.invoke.grpc.HelloWorldClient -Dexec.args="-p 50001 'message one' 'message two'"
* dapr run --protocol grpc --grpc-port 50001 -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.invoke.grpc.HelloWorldClient -Dexec.args="-p 50001 'message one' 'message two'"
*/
public class HelloWorldClient {
/**
* Client mode: class representing a client-side logic for calling HelloWorld over Dapr.
*/
private static class GrpcHelloWorldDaprClient {
/**
* Client mode: class representing a client-side logic for calling HelloWorld over Dapr.
* Client communication channel: host, port and tls(on/off)
*/
private static class GrpcHelloWorldDaprClient {
private final ManagedChannel channel;
/**
* Client communication channel: host, port and tls(on/off)
*/
private final ManagedChannel channel;
/**
* Calls will be done asynchronously.
*/
private final DaprGrpc.DaprFutureStub client;
/**
* Creates a Grpc client for the DaprGrpc service.
* @param host host for the remote service endpoint
* @param port port for the remote service endpoint
*/
public GrpcHelloWorldDaprClient(String host, int port) {
this(ManagedChannelBuilder
.forAddress("localhost", port)
.usePlaintext() // SSL/TLS is default, we turn it off just because this is a sample and not prod.
.build());
}
/**
* Helper constructor to build client from channel.
* @param channel
*/
private GrpcHelloWorldDaprClient(ManagedChannel channel) {
this.channel = channel;
this.client = DaprGrpc.newFutureStub(channel);
}
/**
* Client mode: sends messages, one per second.
* @param messages
*/
private void sendMessages(String... messages) throws ExecutionException, InterruptedException, InvalidProtocolBufferException {
List<ListenableFuture<InvokeServiceResponseEnvelope>> futureResponses = new ArrayList<>();
for (String message : messages)
{
SayRequest request = SayRequest
.newBuilder()
.setMessage(message)
.build();
// Now, wrap the request with Dapr's envelope.
InvokeServiceEnvelope requestEnvelope = InvokeServiceEnvelope
.newBuilder()
.setId("hellogrpc") // Service's identifier.
.setData(Any.pack(request))
.setMethod("say") // The service's method to be invoked by Dapr.
.build();
futureResponses.add(client.invokeService(requestEnvelope));
System.out.println("Client: sent => " + message);
Thread.sleep(TimeUnit.SECONDS.toMillis(10));
}
for (ListenableFuture<InvokeServiceResponseEnvelope> future : futureResponses) {
Any data = future.get().getData(); // Blocks waiting for response.
// IMPORTANT: do not use Any.unpack(), use Type.ParseFrom() instead.
SayResponse response = SayResponse.parseFrom(data.getValue());
System.out.println("Client: got response => " + response.getTimestamp());
}
}
/**
* Client mode: gracefully shutdown client within 1 min, otherwise force it.
* @throws InterruptedException Propagated interrupted exception.
*/
private void shutdown() throws InterruptedException {
this.channel.shutdown().awaitTermination(1, TimeUnit.MINUTES);
System.out.println("Client: Bye.");
}
/**
* Calls will be done asynchronously.
*/
private final DaprGrpc.DaprFutureStub client;
/**
* Creates a Grpc client for the DaprGrpc service.
*
* @param host host for the remote service endpoint
* @param port port for the remote service endpoint
*/
public GrpcHelloWorldDaprClient(String host, int port) {
this(ManagedChannelBuilder
.forAddress("localhost", port)
.usePlaintext() // SSL/TLS is default, we turn it off just because this is a sample and not prod.
.build());
}
public static void main(String[] args) throws Exception {
Options options = new Options();
options.addRequiredOption("p", "port", true, "Port to listen or send event to.");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
// If port string is not valid, it will throw an exception.
int port = Integer.parseInt(cmd.getOptionValue("port"));
GrpcHelloWorldDaprClient helloWorldClient = new GrpcHelloWorldDaprClient("localhost", port);
helloWorldClient.sendMessages(cmd.getArgs());
helloWorldClient.shutdown();
/**
* Helper constructor to build client from channel.
*
* @param channel
*/
private GrpcHelloWorldDaprClient(ManagedChannel channel) {
this.channel = channel;
this.client = DaprGrpc.newFutureStub(channel);
}
/**
* Client mode: sends messages, one per second.
*
* @param messages
*/
private void sendMessages(String... messages) throws ExecutionException, InterruptedException, InvalidProtocolBufferException {
List<ListenableFuture<InvokeServiceResponseEnvelope>> futureResponses = new ArrayList<>();
for (String message : messages) {
SayRequest request = SayRequest
.newBuilder()
.setMessage(message)
.build();
// Now, wrap the request with Dapr's envelope.
InvokeServiceEnvelope requestEnvelope = InvokeServiceEnvelope
.newBuilder()
.setId("hellogrpc") // Service's identifier.
.setData(Any.pack(request))
.setMethod("say") // The service's method to be invoked by Dapr.
.build();
futureResponses.add(client.invokeService(requestEnvelope));
System.out.println("Client: sent => " + message);
Thread.sleep(TimeUnit.SECONDS.toMillis(10));
}
for (ListenableFuture<InvokeServiceResponseEnvelope> future : futureResponses) {
Any data = future.get().getData(); // Blocks waiting for response.
// IMPORTANT: do not use Any.unpack(), use Type.ParseFrom() instead.
SayResponse response = SayResponse.parseFrom(data.getValue());
System.out.println("Client: got response => " + response.getTimestamp());
}
}
/**
* Client mode: gracefully shutdown client within 1 min, otherwise force it.
*
* @throws InterruptedException Propagated interrupted exception.
*/
private void shutdown() throws InterruptedException {
this.channel.shutdown().awaitTermination(1, TimeUnit.MINUTES);
System.out.println("Client: Bye.");
}
}
public static void main(String[] args) throws Exception {
Options options = new Options();
options.addRequiredOption("p", "port", true, "Port to listen or send event to.");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
// If port string is not valid, it will throw an exception.
int port = Integer.parseInt(cmd.getOptionValue("port"));
GrpcHelloWorldDaprClient helloWorldClient = new GrpcHelloWorldDaprClient("localhost", port);
helloWorldClient.sendMessages(cmd.getArgs());
helloWorldClient.shutdown();
}
}

View File

@ -29,112 +29,112 @@ import static io.dapr.examples.DaprExamplesProtos.SayResponse;
*/
public class HelloWorldService {
/**
* Server mode: class that encapsulates all server-side logic for Grpc.
*/
private static class GrpcHelloWorldDaprService extends DaprClientGrpc.DaprClientImplBase {
/**
* Server mode: class that encapsulates all server-side logic for Grpc.
* Format to output date and time.
*/
private static class GrpcHelloWorldDaprService extends DaprClientGrpc.DaprClientImplBase {
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
/**
* Format to output date and time.
*/
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
/**
* Server mode: Grpc server.
*/
private Server server;
/**
* Server mode: Grpc server.
*/
private Server server;
/**
* Server mode: starts listening on given port.
*
* @param port Port to listen on.
* @throws IOException Errors while trying to start service.
*/
private void start(int port) throws IOException {
this.server = ServerBuilder
.forPort(port)
.addService(this)
.build()
.start();
System.out.printf("Server: started listening on port %d\n", port);
/**
* Server mode: starts listening on given port.
*
* @param port Port to listen on.
* @throws IOException Errors while trying to start service.
*/
private void start(int port) throws IOException {
this.server = ServerBuilder
.forPort(port)
.addService(this)
.build()
.start();
System.out.printf("Server: started listening on port %d\n", port);
// Now we handle ctrl+c (or any other JVM shutdown)
Runtime.getRuntime().addShutdownHook(new Thread() {
// Now we handle ctrl+c (or any other JVM shutdown)
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Server: shutting down gracefully ...");
GrpcHelloWorldDaprService.this.server.shutdown();
System.out.println("Server: Bye.");
}
});
}
/**
* Server mode: waits for shutdown trigger.
*
* @throws InterruptedException Propagated interrupted exception.
*/
private void awaitTermination() throws InterruptedException {
if (this.server != null) {
this.server.awaitTermination();
}
}
/**
* Server mode: this is the Dapr method to receive Invoke operations via Grpc.
*
* @param request Dapr envelope request,
* @param responseObserver Dapr envelope response.
*/
@Override
public void onInvoke(DaprClientProtos.InvokeEnvelope request, StreamObserver<Any> responseObserver) {
try {
if ("say".equals(request.getMethod())) {
// IMPORTANT: do not use Any.unpack(), use Type.ParseFrom() instead.
SayRequest sayRequest = SayRequest.parseFrom(request.getData().getValue());
SayResponse sayResponse = this.say(sayRequest);
responseObserver.onNext(Any.pack(sayResponse));
}
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
responseObserver.onError(e);
} finally {
responseObserver.onCompleted();
}
}
/**
* Handling of the 'say' method.
*
* @param request Request to say something.
* @return Response with when it was said.
*/
public SayResponse say(SayRequest request) {
Calendar utcNow = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
String utcNowAsString = DATE_FORMAT.format(utcNow.getTime());
// Handles the request by printing message.
System.out.println("Server: " + request.getMessage() + " @ " + utcNowAsString);
// Now respond with current timestamp.
SayResponse.Builder responseBuilder = SayResponse.newBuilder();
return responseBuilder.setTimestamp(utcNowAsString).build();
public void run() {
System.out.println("Server: shutting down gracefully ...");
GrpcHelloWorldDaprService.this.server.shutdown();
System.out.println("Server: Bye.");
}
});
}
public static void main(String[] args) throws Exception {
Options options = new Options();
options.addRequiredOption("p", "port", true, "Port to listen or send event to.");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
// If port string is not valid, it will throw an exception.
int port = Integer.parseInt(cmd.getOptionValue("port"));
final GrpcHelloWorldDaprService service = new GrpcHelloWorldDaprService();
service.start(port);
service.awaitTermination();
/**
* Server mode: waits for shutdown trigger.
*
* @throws InterruptedException Propagated interrupted exception.
*/
private void awaitTermination() throws InterruptedException {
if (this.server != null) {
this.server.awaitTermination();
}
}
/**
* Server mode: this is the Dapr method to receive Invoke operations via Grpc.
*
* @param request Dapr envelope request,
* @param responseObserver Dapr envelope response.
*/
@Override
public void onInvoke(DaprClientProtos.InvokeEnvelope request, StreamObserver<Any> responseObserver) {
try {
if ("say".equals(request.getMethod())) {
// IMPORTANT: do not use Any.unpack(), use Type.ParseFrom() instead.
SayRequest sayRequest = SayRequest.parseFrom(request.getData().getValue());
SayResponse sayResponse = this.say(sayRequest);
responseObserver.onNext(Any.pack(sayResponse));
}
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
responseObserver.onError(e);
} finally {
responseObserver.onCompleted();
}
}
/**
* Handling of the 'say' method.
*
* @param request Request to say something.
* @return Response with when it was said.
*/
public SayResponse say(SayRequest request) {
Calendar utcNow = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
String utcNowAsString = DATE_FORMAT.format(utcNow.getTime());
// Handles the request by printing message.
System.out.println("Server: " + request.getMessage() + " @ " + utcNowAsString);
// Now respond with current timestamp.
SayResponse.Builder responseBuilder = SayResponse.newBuilder();
return responseBuilder.setTimestamp(utcNowAsString).build();
}
}
public static void main(String[] args) throws Exception {
Options options = new Options();
options.addRequiredOption("p", "port", true, "Port to listen or send event to.");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args);
// If port string is not valid, it will throw an exception.
int port = Integer.parseInt(cmd.getOptionValue("port"));
final GrpcHelloWorldDaprService service = new GrpcHelloWorldDaprService();
service.start(port);
service.awaitTermination();
}
}

View File

@ -16,46 +16,46 @@ import java.util.UUID;
* dapr run --grpc-port 50001 -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.Example
*/
public class Example {
public static void main(String[] args) {
ManagedChannel channel =
ManagedChannelBuilder.forAddress("localhost", 50001).usePlaintext().build();
DaprBlockingStub client = DaprGrpc.newBlockingStub(channel);
public static void main(String[] args) {
ManagedChannel channel =
ManagedChannelBuilder.forAddress("localhost", 50001).usePlaintext().build();
DaprBlockingStub client = DaprGrpc.newBlockingStub(channel);
String key = "mykey";
// First, write key-value pair.
{
String value = UUID.randomUUID().toString();
StateRequest req = StateRequest
.newBuilder()
.setKey(key)
.setValue(Any.newBuilder().setValue(ByteString.copyFromUtf8(value)).build())
.build();
SaveStateEnvelope state = SaveStateEnvelope.newBuilder()
.addRequests(req)
.build();
client.saveState(state);
System.out.println("Saved!");
}
// Now, read it back.
{
GetStateEnvelope req = GetStateEnvelope
.newBuilder()
.setKey(key)
.build();
GetStateResponseEnvelope response = client.getState(req);
String value = response.getData().getValue().toStringUtf8();
System.out.println("Got: " + value);
}
// Then, delete it.
{
DeleteStateEnvelope req = DeleteStateEnvelope
.newBuilder()
.setKey(key)
.build();
client.deleteState(req);
System.out.println("Deleted!");
}
String key = "mykey";
// First, write key-value pair.
{
String value = UUID.randomUUID().toString();
StateRequest req = StateRequest
.newBuilder()
.setKey(key)
.setValue(Any.newBuilder().setValue(ByteString.copyFromUtf8(value)).build())
.build();
SaveStateEnvelope state = SaveStateEnvelope.newBuilder()
.addRequests(req)
.build();
client.saveState(state);
System.out.println("Saved!");
}
// Now, read it back.
{
GetStateEnvelope req = GetStateEnvelope
.newBuilder()
.setKey(key)
.build();
GetStateResponseEnvelope response = client.getState(req);
String value = response.getData().getValue().toStringUtf8();
System.out.println("Got: " + value);
}
// Then, delete it.
{
DeleteStateEnvelope req = DeleteStateEnvelope
.newBuilder()
.setKey(key)
.build();
client.deleteState(req);
System.out.println("Deleted!");
}
}
}

View File

@ -27,117 +27,117 @@ import static java.lang.System.out;
/**
* OrderManager web app.
*
* <p>
* Based on the helloworld Node.js example in https://github.com/dapr/samples/blob/master/1.hello-world/app.js
*
* <p>
* To install jars into your local maven repo:
* mvn clean install
*
* mvn clean install
* <p>
* To run (after step above):
* dapr run --app-id orderapp --app-port 3000 --port 3500 -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.state.http.OrderManager
*
* dapr run --app-id orderapp --app-port 3000 --port 3500 -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.state.http.OrderManager
* <p>
* If this class changes, run this before running it again:
* mvn compile
* mvn compile
*/
public class OrderManager {
static HttpClient httpClient;
static HttpClient httpClient;
public static void main(String[] args) throws IOException {
int httpPort = 3000;
String daprPort = Optional.ofNullable(System.getenv("DAPR_HTTP_PORT")).orElse("3500");
String stateUrl = String.format("http://localhost:%s/v1.0/state", daprPort);
HttpServer httpServer = HttpServer.create(new InetSocketAddress(httpPort), 0);
public static void main(String[] args) throws IOException {
int httpPort = 3000;
String daprPort = Optional.ofNullable(System.getenv("DAPR_HTTP_PORT")).orElse("3500");
String stateUrl = String.format("http://localhost:%s/v1.0/state", daprPort);
HttpServer httpServer = HttpServer.create(new InetSocketAddress(httpPort), 0);
httpClient = HttpClient.newBuilder().version(Version.HTTP_1_1).followRedirects(Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(2)).build();
httpClient = HttpClient.newBuilder().version(Version.HTTP_1_1).followRedirects(Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(2)).build();
httpServer.createContext("/order").setHandler(e -> {
out.println("Fetching order!");
fetch(stateUrl + "/order").thenAccept(response -> {
int resCode = response.statusCode() == 200 ? 200 : 500;
String body = response.statusCode() == 200 ? response.body() : "Could not get state.";
httpServer.createContext("/order").setHandler(e -> {
out.println("Fetching order!");
fetch(stateUrl + "/order").thenAccept(response -> {
int resCode = response.statusCode() == 200 ? 200 : 500;
String body = response.statusCode() == 200 ? response.body() : "Could not get state.";
try {
e.sendResponseHeaders(resCode, body.getBytes().length);
OutputStream os = e.getResponseBody();
try {
os.write(body.getBytes());
} finally {
os.close();
}
} catch (IOException ioerror) {
out.println(ioerror);
}
});
});
httpServer.createContext("/neworder").setHandler(e -> {
try {
out.println("Received new order ...");
String json = readBody(e);
JSONObject jsonObject = new JSONObject(json);
JSONObject data = jsonObject.getJSONObject("data");
String orderId = data.getString("orderId");
out.printf("Got a new order! Order ID: %s\n", orderId);
JSONObject item = new JSONObject();
item.put("key", "order");
item.put("value", data);
JSONArray state = new JSONArray();
state.put(item);
out.printf("Writing to state: %s\n", state.toString());
post(stateUrl, state.toString()).thenAccept(response -> {
int resCode = response.statusCode() == 200 ? 200 : 500;
String body = response.body();
try {
e.sendResponseHeaders(resCode, body.getBytes().length);
OutputStream os = e.getResponseBody();
try {
os.write(body.getBytes());
} finally {
os.close();
}
} catch (IOException ioerror) {
out.println(ioerror);
}
});
} catch (IOException ioerror) {
out.println(ioerror);
}
});
httpServer.start();
out.printf("Java App listening on port %s.", httpPort);
}
private static CompletableFuture<HttpResponse<String>> fetch(String url) {
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).build();
return httpClient.sendAsync(request, BodyHandlers.ofString());
}
private static CompletableFuture<HttpResponse<String>> post(String url, String body) {
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
.header("Content-Type", "application/json; charset=UTF-8").POST(BodyPublishers.ofString(body)).build();
return httpClient.sendAsync(request, BodyHandlers.ofString());
}
private static String readBody(HttpExchange t) throws IOException {
// retrieve the request json data
InputStream is = t.getRequestBody();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) > 0)
bos.write(buffer, 0, len);
} catch (IOException e) {
e.printStackTrace();
} finally {
bos.close();
e.sendResponseHeaders(resCode, body.getBytes().length);
OutputStream os = e.getResponseBody();
try {
os.write(body.getBytes());
} finally {
os.close();
}
} catch (IOException ioerror) {
out.println(ioerror);
}
return new String(bos.toByteArray(), Charset.forName("UTF-8"));
});
});
httpServer.createContext("/neworder").setHandler(e -> {
try {
out.println("Received new order ...");
String json = readBody(e);
JSONObject jsonObject = new JSONObject(json);
JSONObject data = jsonObject.getJSONObject("data");
String orderId = data.getString("orderId");
out.printf("Got a new order! Order ID: %s\n", orderId);
JSONObject item = new JSONObject();
item.put("key", "order");
item.put("value", data);
JSONArray state = new JSONArray();
state.put(item);
out.printf("Writing to state: %s\n", state.toString());
post(stateUrl, state.toString()).thenAccept(response -> {
int resCode = response.statusCode() == 200 ? 200 : 500;
String body = response.body();
try {
e.sendResponseHeaders(resCode, body.getBytes().length);
OutputStream os = e.getResponseBody();
try {
os.write(body.getBytes());
} finally {
os.close();
}
} catch (IOException ioerror) {
out.println(ioerror);
}
});
} catch (IOException ioerror) {
out.println(ioerror);
}
});
httpServer.start();
out.printf("Java App listening on port %s.", httpPort);
}
private static CompletableFuture<HttpResponse<String>> fetch(String url) {
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).build();
return httpClient.sendAsync(request, BodyHandlers.ofString());
}
private static CompletableFuture<HttpResponse<String>> post(String url, String body) {
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url))
.header("Content-Type", "application/json; charset=UTF-8").POST(BodyPublishers.ofString(body)).build();
return httpClient.sendAsync(request, BodyHandlers.ofString());
}
private static String readBody(HttpExchange t) throws IOException {
// retrieve the request json data
InputStream is = t.getRequestBody();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) > 0)
bos.write(buffer, 0, len);
} catch (IOException e) {
e.printStackTrace();
} finally {
bos.close();
}
return new String(bos.toByteArray(), Charset.forName("UTF-8"));
}
}

View File

@ -9,128 +9,134 @@ import java.time.*;
public class ConverterUtils {
/**
* Converts time from the String format used by Dapr into a Duration.
* @param valueString A String representing time in the Dapr runtime's format (e.g. 4h15m50s60ms).
* @return A Duration
*/
public static Duration ConvertDurationFromDaprFormat(String valueString) {
// Convert the format returned by the Dapr runtime into Duration
// An example of the format is: 4h15m50s60ms. It does not include days.
int hIndex = valueString.indexOf('h');
int mIndex = valueString.indexOf('m');
int sIndex = valueString.indexOf('s');
int msIndex = valueString.indexOf("ms");
/**
* Converts time from the String format used by Dapr into a Duration.
*
* @param valueString A String representing time in the Dapr runtime's format (e.g. 4h15m50s60ms).
* @return A Duration
*/
public static Duration ConvertDurationFromDaprFormat(String valueString) {
// Convert the format returned by the Dapr runtime into Duration
// An example of the format is: 4h15m50s60ms. It does not include days.
int hIndex = valueString.indexOf('h');
int mIndex = valueString.indexOf('m');
int sIndex = valueString.indexOf('s');
int msIndex = valueString.indexOf("ms");
String hoursSpan = valueString.substring(0, hIndex);
String hoursSpan = valueString.substring(0, hIndex);
int hours = Integer.parseInt(hoursSpan);
int days = hours / 24;
hours = hours % 24;
int hours = Integer.parseInt(hoursSpan);
int days = hours / 24;
hours = hours % 24;
String minutesSpan = valueString.substring(hIndex + 1, mIndex);
int minutes = Integer.parseInt(minutesSpan);
String minutesSpan = valueString.substring(hIndex + 1, mIndex);
int minutes = Integer.parseInt(minutesSpan);
String secondsSpan = valueString.substring(mIndex + 1, sIndex);
int seconds = Integer.parseInt(secondsSpan);
String secondsSpan = valueString.substring(mIndex + 1, sIndex);
int seconds = Integer.parseInt(secondsSpan);
String millisecondsSpan = valueString.substring(sIndex + 1, msIndex);
int milliseconds = Integer.parseInt(millisecondsSpan);
String millisecondsSpan = valueString.substring(sIndex + 1, msIndex);
int milliseconds = Integer.parseInt(millisecondsSpan);
return Duration.ZERO
.plusDays(days)
.plusHours(hours)
.plusMinutes(minutes)
.plusSeconds(seconds)
.plusMillis(milliseconds);
return Duration.ZERO
.plusDays(days)
.plusHours(hours)
.plusMinutes(minutes)
.plusSeconds(seconds)
.plusMillis(milliseconds);
}
/**
* Converts a Duration to the format used by the Dapr runtime.
*
* @param value Duration
* @return The Duration formatted as a String in the format the Dapr runtime uses (e.g. 4h15m50s60ms)
*/
public static String ConvertDurationToDaprFormat(Duration value) {
String stringValue = "";
// return empty string for anything negative, it'll only happen for reminder "periods", not dueTimes. A
// negative "period" means fire once only.
if (value == Duration.ZERO ||
(value.compareTo(Duration.ZERO) == 1)) {
long hours = getDaysPart(value) * 24 + getHoursPart(value);
StringBuilder sb = new StringBuilder();
sb.append(hours);
sb.append("h");
sb.append(getMinutesPart((value)));
sb.append("m");
sb.append(getSecondsPart((value)));
sb.append("s");
sb.append(getMilliSecondsPart((value)));
sb.append("ms");
return sb.toString();
}
/**
* Converts a Duration to the format used by the Dapr runtime.
* @param value Duration
* @return The Duration formatted as a String in the format the Dapr runtime uses (e.g. 4h15m50s60ms)
*/
public static String ConvertDurationToDaprFormat(Duration value) {
String stringValue = "";
return stringValue;
}
// return empty string for anything negative, it'll only happen for reminder "periods", not dueTimes. A
// negative "period" means fire once only.
if (value == Duration.ZERO ||
(value.compareTo(Duration.ZERO) == 1))
{
long hours = getDaysPart(value) * 24 + getHoursPart(value);
/**
* Helper to get the "days" part of the Duration. For example if the duration is 26 hours, this returns 1.
*
* @param d
* @return
*/
static long getDaysPart(Duration d) {
long t = d.getSeconds() / 60 / 60 / 24;
return t;
}
StringBuilder sb = new StringBuilder();
/**
* Helper to get the "hours" part of the Duration. For example if the duration is 26 hours, this is 1 day, 2 hours, so this returns 2.
*
* @param The duration to parse
* @return the hour part of the duration
*/
static long getHoursPart(Duration d) {
long u = (d.getSeconds() / 60 / 60) % 24;
sb.append(hours);
sb.append("h");
return u;
}
sb.append(getMinutesPart((value)));
sb.append("m");
/**
* Helper to get the "minutes" part of the Duration.
*
* @param The duration to parse
* @return the minutes part of the duration
*/
static long getMinutesPart(Duration d) {
long u = (d.getSeconds() / 60) % 60;
sb.append(getSecondsPart((value)));
sb.append("s");
return u;
}
sb.append(getMilliSecondsPart((value)));
sb.append("ms");
/**
* Helper to get the "seconds" part of the Duration.
*
* @param The duration to parse
* @return the seconds part of the duration
*/
static long getSecondsPart(Duration d) {
long u = d.getSeconds() % 60;
return sb.toString();
}
return u;
}
return stringValue;
}
/**
* Helper to get the "millis" part of the Duration.
*
* @param The duration to parse
* @return the milliseconds part of the duration
*/
static long getMilliSecondsPart(Duration d) {
long u = d.toMillis() % 1000;
/**
* Helper to get the "days" part of the Duration. For example if the duration is 26 hours, this returns 1.
* @param d
* @return
*/
static long getDaysPart(Duration d) {
long t = d.getSeconds() / 60 / 60 / 24;
return t;
}
/**
* Helper to get the "hours" part of the Duration. For example if the duration is 26 hours, this is 1 day, 2 hours, so this returns 2.
* @param The duration to parse
* @return the hour part of the duration
*/
static long getHoursPart(Duration d) {
long u = (d.getSeconds() / 60 / 60) % 24;
return u;
}
/**
* Helper to get the "minutes" part of the Duration.
* @param The duration to parse
* @return the minutes part of the duration
*/
static long getMinutesPart(Duration d) {
long u = (d.getSeconds() / 60) % 60;
return u;
}
/**
* Helper to get the "seconds" part of the Duration.
* @param The duration to parse
* @return the seconds part of the duration
*/
static long getSecondsPart(Duration d) {
long u = d.getSeconds() % 60;
return u;
}
/**
* Helper to get the "millis" part of the Duration.
* @param The duration to parse
* @return the milliseconds part of the duration
*/
static long getMilliSecondsPart(Duration d) {
long u = d.toMillis() % 1000;
return u;
}
return u;
}
}

View File

@ -5,6 +5,7 @@
package io.dapr.actors;
import java.util.*;
import org.junit.Assert;
import org.junit.Test;

View File

@ -10,7 +10,7 @@ import org.junit.Test;
/**
* Integration test for the HTTP Async Client.
*
* <p>
* Requires Dapr running.
*/
public class DaprHttpAsyncClientIT {
@ -23,21 +23,21 @@ public class DaprHttpAsyncClientIT {
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;
.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();
}
}

View File

@ -17,38 +17,37 @@ import java.util.ArrayList;
*/
public class ActorMethodInfoMapTest {
@Test
public void normalUsage() {
ArrayList<Class<TestActor>> interfaceTypes = new ArrayList<Class<TestActor>>();
interfaceTypes.add(TestActor.class);
ActorMethodInfoMap m = new ActorMethodInfoMap(interfaceTypes);
@Test
public void normalUsage() {
ArrayList<Class<TestActor>> interfaceTypes = new ArrayList<Class<TestActor>>();
interfaceTypes.add(TestActor.class);
ActorMethodInfoMap m = new ActorMethodInfoMap(interfaceTypes);
try {
Method m1 = m.LookupActorMethodInfo("getData");
Assert.assertEquals("getData", m1.getName());
Class c = m1.getReturnType();
Assert.assertEquals(c.getClass(), String.class.getClass());
Parameter[] p = m1.getParameters();
Assert.assertEquals(p[0].getType().getClass(), String.class.getClass());
}
catch(Exception e) {
Assert.fail("Exception not expected.");
}
try {
Method m1 = m.LookupActorMethodInfo("getData");
Assert.assertEquals("getData", m1.getName());
Class c = m1.getReturnType();
Assert.assertEquals(c.getClass(), String.class.getClass());
Parameter[] p = m1.getParameters();
Assert.assertEquals(p[0].getType().getClass(), String.class.getClass());
} catch (Exception e) {
Assert.fail("Exception not expected.");
}
}
@Test(expected = NoSuchMethodException.class)
public void lookUpNonExistingMethod() throws NoSuchMethodException {
ArrayList<Class<TestActor>> interfaceTypes = new ArrayList<Class<TestActor>>();
interfaceTypes.add(TestActor.class);
ActorMethodInfoMap m = new ActorMethodInfoMap(interfaceTypes);
@Test(expected = NoSuchMethodException.class)
public void lookUpNonExistingMethod() throws NoSuchMethodException {
ArrayList<Class<TestActor>> interfaceTypes = new ArrayList<Class<TestActor>>();
interfaceTypes.add(TestActor.class);
ActorMethodInfoMap m = new ActorMethodInfoMap(interfaceTypes);
m.LookupActorMethodInfo("thisMethodDoesNotExist");
}
m.LookupActorMethodInfo("thisMethodDoesNotExist");
}
/**
* Only used for this test.
*/
public interface TestActor extends Actor {
String getData(String key);
}
/**
* Only used for this test.
*/
public interface TestActor extends Actor {
String getData(String key);
}
}

View File

@ -13,82 +13,82 @@ import org.junit.Test;
*/
public class ActorTypeInformationTest {
/**
* Actor interfaced used in this test only.
*/
private interface MyActor extends Actor {
/**
* Actor interfaced used in this test only.
*/
private interface MyActor extends Actor {
}
/**
* Checks information for a non-remindable actor.
*/
@Test
public void notRemindable() {
class A extends AbstractActor implements MyActor {
}
/**
* Checks information for a non-remindable actor.
*/
@Test
public void notRemindable() {
ActorTypeInformation info = ActorTypeInformation.create(A.class);
Assert.assertNotNull(info);
Assert.assertEquals("A", info.getName());
Assert.assertEquals(A.class, info.getImplementationClass());
Assert.assertFalse(info.isAbstractClass());
Assert.assertFalse(info.isRemindable());
Assert.assertEquals(1, info.getInterfaces().size());
Assert.assertTrue(info.getInterfaces().contains(MyActor.class));
}
class A extends AbstractActor implements MyActor {
}
/**
* Checks information for a remindable actor.
*/
@Test
public void remindable() {
ActorTypeInformation info = ActorTypeInformation.create(A.class);
Assert.assertNotNull(info);
Assert.assertEquals("A", info.getName());
Assert.assertEquals(A.class, info.getImplementationClass());
Assert.assertFalse(info.isAbstractClass());
Assert.assertFalse(info.isRemindable());
Assert.assertEquals(1, info.getInterfaces().size());
Assert.assertTrue(info.getInterfaces().contains(MyActor.class));
class A extends AbstractActor implements MyActor, Remindable {
}
/**
* Checks information for a remindable actor.
*/
@Test
public void remindable() {
ActorTypeInformation info = ActorTypeInformation.create(A.class);
Assert.assertNotNull(info);
Assert.assertEquals("A", info.getName());
Assert.assertEquals(A.class, info.getImplementationClass());
Assert.assertFalse(info.isAbstractClass());
Assert.assertTrue(info.isRemindable());
Assert.assertEquals(2, info.getInterfaces().size());
Assert.assertTrue(info.getInterfaces().contains(Remindable.class));
Assert.assertTrue(info.getInterfaces().contains(MyActor.class));
}
class A extends AbstractActor implements MyActor, Remindable {
}
ActorTypeInformation info = ActorTypeInformation.create(A.class);
Assert.assertNotNull(info);
Assert.assertEquals("A", info.getName());
Assert.assertEquals(A.class, info.getImplementationClass());
Assert.assertFalse(info.isAbstractClass());
Assert.assertTrue(info.isRemindable());
Assert.assertEquals(2, info.getInterfaces().size());
Assert.assertTrue(info.getInterfaces().contains(Remindable.class));
Assert.assertTrue(info.getInterfaces().contains(MyActor.class));
/**
* Checks information for an actor renamed via annotation.
*/
@Test
public void renamedWithAnnotation() {
@ActorType(Name = "B")
class A extends AbstractActor implements MyActor {
}
/**
* Checks information for an actor renamed via annotation.
*/
@Test
public void renamedWithAnnotation() {
@ActorType(Name = "B")
class A extends AbstractActor implements MyActor {
}
ActorTypeInformation info = ActorTypeInformation.create(A.class);
Assert.assertNotNull(info);
Assert.assertEquals("B", info.getName());
Assert.assertEquals(A.class, info.getImplementationClass());
Assert.assertFalse(info.isAbstractClass());
Assert.assertFalse(info.isRemindable());
Assert.assertEquals(1, info.getInterfaces().size());
Assert.assertTrue(info.getInterfaces().contains(MyActor.class));
}
ActorTypeInformation info = ActorTypeInformation.create(A.class);
Assert.assertNotNull(info);
Assert.assertEquals("B", info.getName());
Assert.assertEquals(A.class, info.getImplementationClass());
Assert.assertFalse(info.isAbstractClass());
Assert.assertFalse(info.isRemindable());
Assert.assertEquals(1, info.getInterfaces().size());
Assert.assertTrue(info.getInterfaces().contains(MyActor.class));
/**
* Checks information for an actor is invalid due to an non-actor parent.
*/
@Test
public void nonActorParentClass() {
abstract class MyAbstractClass extends AbstractActor implements MyActor {
}
/**
* Checks information for an actor is invalid due to an non-actor parent.
*/
@Test
public void nonActorParentClass() {
abstract class MyAbstractClass extends AbstractActor implements MyActor {
}
class A extends MyAbstractClass {
}
ActorTypeInformation info = ActorTypeInformation.tryCreate(A.class);
Assert.assertNull(info);
class A extends MyAbstractClass {
}
ActorTypeInformation info = ActorTypeInformation.tryCreate(A.class);
Assert.assertNull(info);
}
}

View File

@ -7,95 +7,95 @@ import java.time.Duration;
public class ConverterUtilsTest {
@Test
public void convertTimeBothWays() {
String s = "4h15m50s60ms";
Duration d1 = ConverterUtils.ConvertDurationFromDaprFormat(s);
@Test
public void convertTimeBothWays() {
String s = "4h15m50s60ms";
Duration d1 = ConverterUtils.ConvertDurationFromDaprFormat(s);
String t = ConverterUtils.ConvertDurationToDaprFormat(d1);
Assert.assertEquals(s, t);
}
String t = ConverterUtils.ConvertDurationToDaprFormat(d1);
Assert.assertEquals(s, t);
}
@Test
public void largeHours() {
// hours part is larger than 24
String s = "31h15m50s60ms";
Duration d1 = ConverterUtils.ConvertDurationFromDaprFormat(s);
@Test
public void largeHours() {
// hours part is larger than 24
String s = "31h15m50s60ms";
Duration d1 = ConverterUtils.ConvertDurationFromDaprFormat(s);
String t = ConverterUtils.ConvertDurationToDaprFormat(d1);
Assert.assertEquals(s, t);
}
String t = ConverterUtils.ConvertDurationToDaprFormat(d1);
Assert.assertEquals(s, t);
}
@Test
public void negativeDuration() {
Duration d = Duration.ofSeconds(-99);
String t = ConverterUtils.ConvertDurationToDaprFormat(d);
Assert.assertEquals("", t);
}
@Test
public void negativeDuration() {
Duration d = Duration.ofSeconds(-99);
String t = ConverterUtils.ConvertDurationToDaprFormat(d);
Assert.assertEquals("", t);
}
@Test
public void testGetHoursPart() {
Duration d1 = Duration.ZERO.plusHours(26);
Assert.assertEquals(2, ConverterUtils.getHoursPart(d1));
@Test
public void testGetHoursPart() {
Duration d1 = Duration.ZERO.plusHours(26);
Assert.assertEquals(2, ConverterUtils.getHoursPart(d1));
Duration d2 = Duration.ZERO.plusHours(23);
Assert.assertEquals(23, ConverterUtils.getHoursPart(d2));
Duration d2 = Duration.ZERO.plusHours(23);
Assert.assertEquals(23, ConverterUtils.getHoursPart(d2));
Duration d3 = Duration.ZERO.plusHours(24);
Assert.assertEquals(0, ConverterUtils.getHoursPart(d3));
}
Duration d3 = Duration.ZERO.plusHours(24);
Assert.assertEquals(0, ConverterUtils.getHoursPart(d3));
}
@Test
public void testGetMinutesPart() {
Duration d1 = Duration.ZERO.plusMinutes(61);
Assert.assertEquals(1, ConverterUtils.getMinutesPart(d1));
@Test
public void testGetMinutesPart() {
Duration d1 = Duration.ZERO.plusMinutes(61);
Assert.assertEquals(1, ConverterUtils.getMinutesPart(d1));
Duration d2 = Duration.ZERO.plusMinutes(60);
Assert.assertEquals(0, ConverterUtils.getMinutesPart(d2));
Duration d2 = Duration.ZERO.plusMinutes(60);
Assert.assertEquals(0, ConverterUtils.getMinutesPart(d2));
Duration d3 = Duration.ZERO.plusMinutes(59);
Assert.assertEquals(59, ConverterUtils.getMinutesPart(d3));
Duration d3 = Duration.ZERO.plusMinutes(59);
Assert.assertEquals(59, ConverterUtils.getMinutesPart(d3));
Duration d4 = Duration.ZERO.plusMinutes(3600);
Assert.assertEquals(0, ConverterUtils.getMinutesPart(d4));
}
Duration d4 = Duration.ZERO.plusMinutes(3600);
Assert.assertEquals(0, ConverterUtils.getMinutesPart(d4));
}
@Test
public void testGetSecondsPart() {
Duration d1 = Duration.ZERO.plusSeconds(61);
Assert.assertEquals(1, ConverterUtils.getSecondsPart(d1));
@Test
public void testGetSecondsPart() {
Duration d1 = Duration.ZERO.plusSeconds(61);
Assert.assertEquals(1, ConverterUtils.getSecondsPart(d1));
Duration d2 = Duration.ZERO.plusSeconds(60);
Assert.assertEquals(0, ConverterUtils.getSecondsPart(d2));
Duration d2 = Duration.ZERO.plusSeconds(60);
Assert.assertEquals(0, ConverterUtils.getSecondsPart(d2));
Duration d3 = Duration.ZERO.plusSeconds(59);
Assert.assertEquals(59, ConverterUtils.getSecondsPart(d3));
Duration d3 = Duration.ZERO.plusSeconds(59);
Assert.assertEquals(59, ConverterUtils.getSecondsPart(d3));
Duration d4 = Duration.ZERO.plusSeconds(3600);
Assert.assertEquals(0, ConverterUtils.getSecondsPart(d4));
}
Duration d4 = Duration.ZERO.plusSeconds(3600);
Assert.assertEquals(0, ConverterUtils.getSecondsPart(d4));
}
@Test
public void testGetMillisecondsPart() {
Duration d1 = Duration.ZERO.plusMillis(61);
Assert.assertEquals(61, ConverterUtils.getMilliSecondsPart(d1));
@Test
public void testGetMillisecondsPart() {
Duration d1 = Duration.ZERO.plusMillis(61);
Assert.assertEquals(61, ConverterUtils.getMilliSecondsPart(d1));
Duration d2 = Duration.ZERO.plusMillis(60);
Assert.assertEquals(60, ConverterUtils.getMilliSecondsPart(d2));
Duration d2 = Duration.ZERO.plusMillis(60);
Assert.assertEquals(60, ConverterUtils.getMilliSecondsPart(d2));
Duration d3 = Duration.ZERO.plusMillis(59);
Assert.assertEquals(59, ConverterUtils.getMilliSecondsPart(d3));
Duration d3 = Duration.ZERO.plusMillis(59);
Assert.assertEquals(59, ConverterUtils.getMilliSecondsPart(d3));
Duration d4 = Duration.ZERO.plusMillis(999);
Assert.assertEquals(999, ConverterUtils.getMilliSecondsPart(d4));
Duration d4 = Duration.ZERO.plusMillis(999);
Assert.assertEquals(999, ConverterUtils.getMilliSecondsPart(d4));
Duration d5 = Duration.ZERO.plusMillis(1001);
Assert.assertEquals(1, ConverterUtils.getMilliSecondsPart(d5));
Duration d5 = Duration.ZERO.plusMillis(1001);
Assert.assertEquals(1, ConverterUtils.getMilliSecondsPart(d5));
Duration d6 = Duration.ZERO.plusMillis(1000);
Assert.assertEquals(0, ConverterUtils.getMilliSecondsPart(d6));
Duration d6 = Duration.ZERO.plusMillis(1000);
Assert.assertEquals(0, ConverterUtils.getMilliSecondsPart(d6));
Duration d7 = Duration.ZERO.plusMillis(10000);
Assert.assertEquals(0, ConverterUtils.getMilliSecondsPart(d7));
}
Duration d7 = Duration.ZERO.plusMillis(10000);
Assert.assertEquals(0, ConverterUtils.getMilliSecondsPart(d7));
}
}