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. * Client that will use Actor.
*/ */
public class ActorClient { 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. * Example of implementation of an Actor.
*/ */
public interface DemoActor { 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. * Implementation of the DemoActor for the server side.
*/ */
public class DemoActorImpl { public class DemoActorImpl {
// TODO. // TODO.
} }

View File

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

View File

@ -23,105 +23,108 @@ import static io.dapr.examples.DaprExamplesProtos.SayResponse;
/** /**
* 1. Build and install jars: * 1. Build and install jars:
* mvn clean install * mvn clean install
* 2. Send messages to the server: * 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 { 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) * Calls will be done asynchronously.
*/ */
private final ManagedChannel channel; private final DaprGrpc.DaprFutureStub client;
/**
* 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.");
}
/**
* 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(); * Helper constructor to build client from channel.
options.addRequiredOption("p", "port", true, "Port to listen or send event to."); *
* @param channel
CommandLineParser parser = new DefaultParser(); */
CommandLine cmd = parser.parse(options, args); private GrpcHelloWorldDaprClient(ManagedChannel channel) {
this.channel = channel;
// If port string is not valid, it will throw an exception. this.client = DaprGrpc.newFutureStub(channel);
int port = Integer.parseInt(cmd.getOptionValue("port"));
GrpcHelloWorldDaprClient helloWorldClient = new GrpcHelloWorldDaprClient("localhost", port);
helloWorldClient.sendMessages(cmd.getArgs());
helloWorldClient.shutdown();
} }
/**
* 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 { 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. * Server mode: Grpc server.
*/ */
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private Server server;
/** /**
* Server mode: Grpc server. * Server mode: starts listening on given port.
*/ *
private Server server; * @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)
* Server mode: starts listening on given port. Runtime.getRuntime().addShutdownHook(new Thread() {
*
* @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() {
@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 @Override
public void onInvoke(DaprClientProtos.InvokeEnvelope request, StreamObserver<Any> responseObserver) { public void run() {
try { System.out.println("Server: shutting down gracefully ...");
if ("say".equals(request.getMethod())) { GrpcHelloWorldDaprService.this.server.shutdown();
// IMPORTANT: do not use Any.unpack(), use Type.ParseFrom() instead. System.out.println("Server: Bye.");
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(); * Server mode: waits for shutdown trigger.
options.addRequiredOption("p", "port", true, "Port to listen or send event to."); *
* @throws InterruptedException Propagated interrupted exception.
CommandLineParser parser = new DefaultParser(); */
CommandLine cmd = parser.parse(options, args); private void awaitTermination() throws InterruptedException {
if (this.server != null) {
// If port string is not valid, it will throw an exception. this.server.awaitTermination();
int port = Integer.parseInt(cmd.getOptionValue("port")); }
final GrpcHelloWorldDaprService service = new GrpcHelloWorldDaprService();
service.start(port);
service.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 * dapr run --grpc-port 50001 -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.Example
*/ */
public class Example { public class Example {
public static void main(String[] args) { public static void main(String[] args) {
ManagedChannel channel = ManagedChannel channel =
ManagedChannelBuilder.forAddress("localhost", 50001).usePlaintext().build(); ManagedChannelBuilder.forAddress("localhost", 50001).usePlaintext().build();
DaprBlockingStub client = DaprGrpc.newBlockingStub(channel); DaprBlockingStub client = DaprGrpc.newBlockingStub(channel);
String key = "mykey"; String key = "mykey";
// First, write key-value pair. // First, write key-value pair.
{ {
String value = UUID.randomUUID().toString(); String value = UUID.randomUUID().toString();
StateRequest req = StateRequest StateRequest req = StateRequest
.newBuilder() .newBuilder()
.setKey(key) .setKey(key)
.setValue(Any.newBuilder().setValue(ByteString.copyFromUtf8(value)).build()) .setValue(Any.newBuilder().setValue(ByteString.copyFromUtf8(value)).build())
.build(); .build();
SaveStateEnvelope state = SaveStateEnvelope.newBuilder() SaveStateEnvelope state = SaveStateEnvelope.newBuilder()
.addRequests(req) .addRequests(req)
.build(); .build();
client.saveState(state); client.saveState(state);
System.out.println("Saved!"); 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!");
}
} }
// 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. * OrderManager web app.
* * <p>
* Based on the helloworld Node.js example in https://github.com/dapr/samples/blob/master/1.hello-world/app.js * 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: * To install jars into your local maven repo:
* mvn clean install * mvn clean install
* * <p>
* To run (after step above): * 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: * If this class changes, run this before running it again:
* mvn compile * mvn compile
*/ */
public class OrderManager { public class OrderManager {
static HttpClient httpClient; static HttpClient httpClient;
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
int httpPort = 3000; int httpPort = 3000;
String daprPort = Optional.ofNullable(System.getenv("DAPR_HTTP_PORT")).orElse("3500"); String daprPort = Optional.ofNullable(System.getenv("DAPR_HTTP_PORT")).orElse("3500");
String stateUrl = String.format("http://localhost:%s/v1.0/state", daprPort); String stateUrl = String.format("http://localhost:%s/v1.0/state", daprPort);
HttpServer httpServer = HttpServer.create(new InetSocketAddress(httpPort), 0); HttpServer httpServer = HttpServer.create(new InetSocketAddress(httpPort), 0);
httpClient = HttpClient.newBuilder().version(Version.HTTP_1_1).followRedirects(Redirect.NORMAL) httpClient = HttpClient.newBuilder().version(Version.HTTP_1_1).followRedirects(Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(2)).build(); .connectTimeout(Duration.ofSeconds(2)).build();
httpServer.createContext("/order").setHandler(e -> { httpServer.createContext("/order").setHandler(e -> {
out.println("Fetching order!"); out.println("Fetching order!");
fetch(stateUrl + "/order").thenAccept(response -> { fetch(stateUrl + "/order").thenAccept(response -> {
int resCode = response.statusCode() == 200 ? 200 : 500; int resCode = response.statusCode() == 200 ? 200 : 500;
String body = response.statusCode() == 200 ? response.body() : "Could not get state."; 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 { try {
while ((len = is.read(buffer)) > 0) e.sendResponseHeaders(resCode, body.getBytes().length);
bos.write(buffer, 0, len); OutputStream os = e.getResponseBody();
} catch (IOException e) { try {
e.printStackTrace(); os.write(body.getBytes());
} finally { } finally {
bos.close(); 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 { public class ConverterUtils {
/** /**
* Converts time from the String format used by Dapr into a Duration. * 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 * @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 public static Duration ConvertDurationFromDaprFormat(String valueString) {
// An example of the format is: 4h15m50s60ms. It does not include days. // Convert the format returned by the Dapr runtime into Duration
int hIndex = valueString.indexOf('h'); // An example of the format is: 4h15m50s60ms. It does not include days.
int mIndex = valueString.indexOf('m'); int hIndex = valueString.indexOf('h');
int sIndex = valueString.indexOf('s'); int mIndex = valueString.indexOf('m');
int msIndex = valueString.indexOf("ms"); 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 hours = Integer.parseInt(hoursSpan);
int days = hours / 24; int days = hours / 24;
hours = hours % 24; hours = hours % 24;
String minutesSpan = valueString.substring(hIndex + 1, mIndex); String minutesSpan = valueString.substring(hIndex + 1, mIndex);
int minutes = Integer.parseInt(minutesSpan); int minutes = Integer.parseInt(minutesSpan);
String secondsSpan = valueString.substring(mIndex + 1, sIndex); String secondsSpan = valueString.substring(mIndex + 1, sIndex);
int seconds = Integer.parseInt(secondsSpan); int seconds = Integer.parseInt(secondsSpan);
String millisecondsSpan = valueString.substring(sIndex + 1, msIndex); String millisecondsSpan = valueString.substring(sIndex + 1, msIndex);
int milliseconds = Integer.parseInt(millisecondsSpan); int milliseconds = Integer.parseInt(millisecondsSpan);
return Duration.ZERO return Duration.ZERO
.plusDays(days) .plusDays(days)
.plusHours(hours) .plusHours(hours)
.plusMinutes(minutes) .plusMinutes(minutes)
.plusSeconds(seconds) .plusSeconds(seconds)
.plusMillis(milliseconds); .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();
} }
/** return stringValue;
* 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. * Helper to get the "days" part of the Duration. For example if the duration is 26 hours, this returns 1.
if (value == Duration.ZERO || *
(value.compareTo(Duration.ZERO) == 1)) * @param d
{ * @return
long hours = getDaysPart(value) * 24 + getHoursPart(value); */
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); return u;
sb.append("h"); }
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))); return u;
sb.append("s"); }
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;
/** return u;
* 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;
}
} }

View File

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

View File

@ -10,7 +10,7 @@ import org.junit.Test;
/** /**
* Integration test for the HTTP Async Client. * Integration test for the HTTP Async Client.
* * <p>
* Requires Dapr running. * Requires Dapr running.
*/ */
public class DaprHttpAsyncClientIT { public class DaprHttpAsyncClientIT {
@ -23,21 +23,21 @@ public class DaprHttpAsyncClientIT {
public void invokeUnknownActor() { public void invokeUnknownActor() {
ActorProxyAsyncClient daprAsyncClient = new ActorProxyClientBuilder().buildAsyncClient(); ActorProxyAsyncClient daprAsyncClient = new ActorProxyClientBuilder().buildAsyncClient();
daprAsyncClient daprAsyncClient
.invokeActorMethod("ActorThatDoesNotExist", "100", "GetData", null) .invokeActorMethod("ActorThatDoesNotExist", "100", "GetData", null)
.doOnError(x -> { .doOnError(x -> {
Assert.assertTrue(x instanceof RuntimeException); Assert.assertTrue(x instanceof RuntimeException);
RuntimeException runtimeException = (RuntimeException) x; RuntimeException runtimeException = (RuntimeException) x;
Throwable cause = runtimeException.getCause(); Throwable cause = runtimeException.getCause();
Assert.assertTrue(cause instanceof DaprException); Assert.assertTrue(cause instanceof DaprException);
DaprException daprException = (DaprException) cause; DaprException daprException = (DaprException) cause;
Assert.assertNotNull(daprException); Assert.assertNotNull(daprException);
Assert.assertEquals("ERR_INVOKE_ACTOR", daprException.getErrorCode()); Assert.assertEquals("ERR_INVOKE_ACTOR", daprException.getErrorCode());
Assert.assertNotNull(daprException.getMessage()); Assert.assertNotNull(daprException.getMessage());
Assert.assertFalse(daprException.getMessage().isEmpty()); Assert.assertFalse(daprException.getMessage().isEmpty());
}) })
.doOnSuccess(x -> Assert.fail("This call should fail.")) .doOnSuccess(x -> Assert.fail("This call should fail."))
.block(); .block();
} }
} }

View File

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

View File

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

View File

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