Fixes checkstyle in existing code and enables error on checkstyle warning (#172)

* checkstyle

* Fix checkstyle and enable build error on checkstyle warning

* Merge from master
This commit is contained in:
Leon Mai 2020-01-29 23:19:38 -08:00 committed by GitHub
parent 91ac017f7f
commit 313730c308
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
44 changed files with 991 additions and 715 deletions

View File

@ -8,7 +8,6 @@ package io.dapr.examples.actors.http;
import io.dapr.actors.ActorId; import io.dapr.actors.ActorId;
import io.dapr.actors.client.ActorProxy; import io.dapr.actors.client.ActorProxy;
import io.dapr.actors.client.ActorProxyBuilder; import io.dapr.actors.client.ActorProxyBuilder;
import io.dapr.serializer.DefaultObjectSerializer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -22,7 +21,8 @@ import java.util.concurrent.TimeUnit;
* 1. Build and install jars: * 1. Build and install jars:
* mvn clean install * mvn clean install
* 2. Run the client: * 2. Run the client:
* dapr run --app-id demoactorclient --port 3006 -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.actors.http.DemoActorClient * dapr run --app-id demoactorclient --port 3006 -- mvn exec:java \
* -pl=examples -Dexec.mainClass=io.dapr.examples.actors.http.DemoActorClient
*/ */
public class DemoActorClient { public class DemoActorClient {
@ -34,6 +34,11 @@ public class DemoActorClient {
private static final ExecutorService POOL = Executors.newFixedThreadPool(NUM_ACTORS); private static final ExecutorService POOL = Executors.newFixedThreadPool(NUM_ACTORS);
/**
* The main method.
* @param args Unused.
* @throws Exception An Exception.
*/
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
ActorProxyBuilder builder = new ActorProxyBuilder("DemoActor"); ActorProxyBuilder builder = new ActorProxyBuilder("DemoActor");
@ -57,10 +62,10 @@ public class DemoActorClient {
for (int i = 0; i < NUM_MESSAGES_PER_ACTOR; i++) { for (int i = 0; i < NUM_MESSAGES_PER_ACTOR; i++) {
actor.invokeActorMethod("incrementAndGet", 1).block(); actor.invokeActorMethod("incrementAndGet", 1).block();
String result = actor.invokeActorMethod(METHOD_NAME, String result = actor.invokeActorMethod(METHOD_NAME,
String.format("Actor %s said message #%d", actor.getActorId().toString(), i), String.class).block(); String.format("Actor %s said message #%d", actor.getActorId().toString(), i), String.class).block();
System.out.println(String.format("Actor %s got a reply: %s", actor.getActorId().toString(), result)); System.out.println(String.format("Actor %s got a reply: %s", actor.getActorId().toString(), result));
try { try {
Thread.sleep((long)(1000 * Math.random())); Thread.sleep((long) (1000 * Math.random()));
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
@ -69,7 +74,7 @@ public class DemoActorClient {
} }
System.out.println( System.out.println(
"Messages sent: " + actor.invokeActorMethod("incrementAndGet", 0, int.class).block()); "Messages sent: " + actor.invokeActorMethod("incrementAndGet", 0, int.class).block());
}, POOL); }, POOL);
} }
} }

View File

@ -10,7 +10,6 @@ import io.dapr.actors.runtime.AbstractActor;
import io.dapr.actors.runtime.ActorRuntimeContext; import io.dapr.actors.runtime.ActorRuntimeContext;
import io.dapr.actors.runtime.ActorType; import io.dapr.actors.runtime.ActorType;
import io.dapr.actors.runtime.Remindable; import io.dapr.actors.runtime.Remindable;
import reactor.core.publisher.Mono;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@ -18,6 +17,8 @@ import java.time.Duration;
import java.util.Calendar; import java.util.Calendar;
import java.util.TimeZone; import java.util.TimeZone;
import reactor.core.publisher.Mono;
/** /**
* Implementation of the DemoActor for the server side. * Implementation of the DemoActor for the server side.
*/ */
@ -29,24 +30,29 @@ public class DemoActorImpl extends AbstractActor implements DemoActor, Remindabl
*/ */
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
/**
* This is the constructor of an actor implementation.
* @param runtimeContext The runtime context object which contains objects such as the state provider.
* @param id The id of this actor.
*/
public DemoActorImpl(ActorRuntimeContext runtimeContext, ActorId id) { public DemoActorImpl(ActorRuntimeContext runtimeContext, ActorId id) {
super(runtimeContext, id); super(runtimeContext, id);
super.registerActorTimer( super.registerActorTimer(
null, null,
"clock", "clock",
"ping!", "ping!",
Duration.ofSeconds(2), Duration.ofSeconds(2),
Duration.ofSeconds(1)).block(); Duration.ofSeconds(1)).block();
} }
@Override @Override
public void registerReminder() { public void registerReminder() {
super.registerReminder( super.registerReminder(
"myremind", "myremind",
(int)(Integer.MAX_VALUE * Math.random()), (int) (Integer.MAX_VALUE * Math.random()),
Duration.ofSeconds(5), Duration.ofSeconds(5),
Duration.ofSeconds(2)).block(); Duration.ofSeconds(2)).block();
} }
@Override @Override
@ -55,9 +61,9 @@ public class DemoActorImpl extends AbstractActor implements DemoActor, Remindabl
String utcNowAsString = DATE_FORMAT.format(utcNow.getTime()); String utcNowAsString = DATE_FORMAT.format(utcNow.getTime());
// Handles the request by printing message. // Handles the request by printing message.
System.out.println("Server say method for actor " + System.out.println("Server say method for actor "
super.getId() + ": " + + super.getId() + ": "
(something == null ? "" : something + " @ " + utcNowAsString)); + (something == null ? "" : something + " @ " + utcNowAsString));
super.getActorStateManager().set("lastmessage", something).block(); super.getActorStateManager().set("lastmessage", something).block();
@ -68,9 +74,9 @@ public class DemoActorImpl extends AbstractActor implements DemoActor, Remindabl
@Override @Override
public Mono<Integer> incrementAndGet(int delta) { public Mono<Integer> incrementAndGet(int delta) {
return super.getActorStateManager().contains("counter") return super.getActorStateManager().contains("counter")
.flatMap(exists -> exists ? super.getActorStateManager().get("counter", int.class) : Mono.just(0)) .flatMap(exists -> exists ? super.getActorStateManager().get("counter", int.class) : Mono.just(0))
.map(c -> c + delta) .map(c -> c + delta)
.flatMap(c -> super.getActorStateManager().set("counter", c).thenReturn(c)); .flatMap(c -> super.getActorStateManager().set("counter", c).thenReturn(c));
} }
@Override @Override
@ -79,9 +85,9 @@ public class DemoActorImpl extends AbstractActor implements DemoActor, Remindabl
String utcNowAsString = DATE_FORMAT.format(utcNow.getTime()); String utcNowAsString = DATE_FORMAT.format(utcNow.getTime());
// Handles the request by printing message. // Handles the request by printing message.
System.out.println("Server timer for actor " + System.out.println("Server timer for actor "
super.getId() + ": " + + super.getId() + ": "
(message == null ? "" : message + " @ " + utcNowAsString)); + (message == null ? "" : message + " @ " + utcNowAsString));
} }
@Override @Override
@ -96,8 +102,8 @@ public class DemoActorImpl extends AbstractActor implements DemoActor, Remindabl
// Handles the request by printing message. // Handles the request by printing message.
System.out.println(String.format( System.out.println(String.format(
"Server reminded actor %s of: %s for %d @ %s", "Server reminded actor %s of: %s for %d @ %s",
this.getId(), reminderName, state, utcNowAsString)); this.getId(), reminderName, state, utcNowAsString));
return Mono.empty(); return Mono.empty();
} }
} }

View File

@ -20,14 +20,20 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
* 1. Build and install jars: * 1. Build and install jars:
* mvn clean install * mvn clean install
* 2. Run the server: * 2. Run the server:
* dapr run --app-id demoactorservice --app-port 3000 --port 3005 -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.actors.http.DemoActorService -Dexec.args="-p 3000" * dapr run --app-id demoactorservice --app-port 3000 --port 3005 \
* -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.actors.http.DemoActorService -Dexec.args="-p 3000"
*/ */
@SpringBootApplication @SpringBootApplication
public class DemoActorService { public class DemoActorService {
/**
* The main method of this app.
* @param args The port the app will listen on.
* @throws Exception An Exception.
*/
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Options options = new Options(); Options options = new Options();
options.addRequiredOption("p", "port", true, "Port Dapr will listen to."); options.addRequiredOption("p", "port", true, "Port the will listen to.");
CommandLineParser parser = new DefaultParser(); CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args); CommandLine cmd = parser.parse(options, args);
@ -37,7 +43,7 @@ public class DemoActorService {
// Register the Actor class. // Register the Actor class.
ActorRuntime.getInstance().registerActor( ActorRuntime.getInstance().registerActor(
DemoActorImpl.class, new DefaultObjectSerializer(), new DefaultObjectSerializer()); DemoActorImpl.class, new DefaultObjectSerializer(), new DefaultObjectSerializer());
// Start Dapr's callback endpoint. // Start Dapr's callback endpoint.
DaprApplication.start(port); DaprApplication.start(port);

View File

@ -10,10 +10,8 @@ import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
public class HelloController { public class HelloController {
@RequestMapping("/")
@RequestMapping("/") public String index() {
public String index() { return "Greetings from your Spring Boot Application!";
return "Greetings from your Spring Boot Application!"; }
}
} }

View File

@ -17,13 +17,19 @@ import org.apache.commons.cli.Options;
* mvn clean install * mvn clean install
* 2. cd to [repo-root]/examples * 2. cd to [repo-root]/examples
* 3. Run : * 3. Run :
* dapr run --app-id inputbinding --app-port 3000 --port 3005 -- mvn exec:java -D exec.mainClass=io.dapr.examples.bindings.InputBindingExample -D exec.args="-p 3000" * dapr run --app-id inputbinding --app-port 3000 --port 3005 \
* -- mvn exec:java -D exec.mainClass=io.dapr.examples.bindings.InputBindingExample -D exec.args="-p 3000"
*/ */
public class InputBindingExample { public class InputBindingExample {
/**
* The entry point of this app.
* @param args The port this app will listen on.
* @throws Exception The Exception.
*/
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Options options = new Options(); Options options = new Options();
options.addRequiredOption("p", "port", true, "Port Dapr will listen to."); options.addRequiredOption("p", "port", true, "The port this app will listen on.");
CommandLineParser parser = new DefaultParser(); CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args); CommandLine cmd = parser.parse(options, args);

View File

@ -7,28 +7,36 @@ package io.dapr.examples.bindings;
import io.dapr.client.DaprClient; import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder; import io.dapr.client.DaprClientBuilder;
import io.dapr.serializer.DefaultObjectSerializer;
/** /**
* Service for output binding example. * Service for output binding example.
* 1. From your repo root, build and install jars: * 1. From your repo root, build and install jars:
* mvn clean install * mvn clean install
* 2. cd to [repo-root]/examples * 2. cd to [repo-root]/examples
* 3. Run the program: * 3. Run the program:
* dapr run --app-id outputbinding --port 3006 -- mvn exec:java -D exec.mainClass=io.dapr.examples.bindings.OutputBindingExample * dapr run --app-id outputbinding --port 3006 \
* -- mvn exec:java -D exec.mainClass=io.dapr.examples.bindings.OutputBindingExample
*/ */
public class OutputBindingExample { public class OutputBindingExample {
public static class MyClass { public static class MyClass {
public MyClass(){} public MyClass() {
}
public String message; public String message;
} }
static final String BINDING_NAME = "bindingSample";
/**
* The main method of this app.
*
* @param args Not used.
*/
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public static void main(String[] args) { public static void main(String[] args) {
DaprClient client = new DaprClientBuilder().build(); DaprClient client = new DaprClientBuilder().build();
final String BINDING_NAME = "bindingSample";
// This is an example of sending data in a user-defined object. The input binding will receive: // This is an example of sending data in a user-defined object. The input binding will receive:
// {"message":"hello"} // {"message":"hello"}
MyClass myClass = new MyClass(); MyClass myClass = new MyClass();

View File

@ -1,5 +1,13 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*/
package io.dapr.examples.invoke.grpc; package io.dapr.examples.invoke.grpc;
import static io.dapr.examples.DaprExamplesProtos.SayRequest;
import static io.dapr.examples.DaprExamplesProtos.SayResponse;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
import com.google.protobuf.Any; import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.InvalidProtocolBufferException;
@ -8,24 +16,23 @@ import io.dapr.DaprProtos.InvokeServiceEnvelope;
import io.dapr.DaprProtos.InvokeServiceResponseEnvelope; import io.dapr.DaprProtos.InvokeServiceResponseEnvelope;
import io.grpc.ManagedChannel; import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder; import io.grpc.ManagedChannelBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options; import org.apache.commons.cli.Options;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import static io.dapr.examples.DaprExamplesProtos.SayRequest;
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 {
@ -35,7 +42,7 @@ public class HelloWorldClient {
private static class GrpcHelloWorldDaprClient { private static class GrpcHelloWorldDaprClient {
/** /**
* Client communication channel: host, port and tls(on/off) * Client communication channel: host, port and tls(on/off).
*/ */
private final ManagedChannel channel; private final ManagedChannel channel;
@ -52,15 +59,15 @@ public class HelloWorldClient {
*/ */
public GrpcHelloWorldDaprClient(String host, int port) { public GrpcHelloWorldDaprClient(String host, int port) {
this(ManagedChannelBuilder this(ManagedChannelBuilder
.forAddress("localhost", port) .forAddress("localhost", port)
.usePlaintext() // SSL/TLS is default, we turn it off just because this is a sample and not prod. .usePlaintext() // SSL/TLS is default, we turn it off just because this is a sample and not prod.
.build()); .build());
} }
/** /**
* Helper constructor to build client from channel. * Helper constructor to build client from channel.
* *
* @param channel * @param channel The ManagedChannel.
*/ */
private GrpcHelloWorldDaprClient(ManagedChannel channel) { private GrpcHelloWorldDaprClient(ManagedChannel channel) {
this.channel = channel; this.channel = channel;
@ -70,23 +77,24 @@ public class HelloWorldClient {
/** /**
* Client mode: sends messages, one per second. * Client mode: sends messages, one per second.
* *
* @param messages * @param messages The messages to send.
*/ */
private void sendMessages(String... messages) throws ExecutionException, InterruptedException, InvalidProtocolBufferException { private void sendMessages(String... messages)
throws ExecutionException, InterruptedException, InvalidProtocolBufferException {
List<ListenableFuture<InvokeServiceResponseEnvelope>> futureResponses = new ArrayList<>(); List<ListenableFuture<InvokeServiceResponseEnvelope>> futureResponses = new ArrayList<>();
for (String message : messages) { for (String message : messages) {
SayRequest request = SayRequest SayRequest request = SayRequest
.newBuilder() .newBuilder()
.setMessage(message) .setMessage(message)
.build(); .build();
// Now, wrap the request with Dapr's envelope. // Now, wrap the request with Dapr's envelope.
InvokeServiceEnvelope requestEnvelope = InvokeServiceEnvelope InvokeServiceEnvelope requestEnvelope = InvokeServiceEnvelope
.newBuilder() .newBuilder()
.setId("hellogrpc") // Service's identifier. .setId("hellogrpc") // Service's identifier.
.setData(Any.pack(request)) .setData(Any.pack(request))
.setMethod("say") // The service's method to be invoked by Dapr. .setMethod("say") // The service's method to be invoked by Dapr.
.build(); .build();
futureResponses.add(client.invokeService(requestEnvelope)); futureResponses.add(client.invokeService(requestEnvelope));
System.out.println("Client: sent => " + message); System.out.println("Client: sent => " + message);
@ -113,6 +121,12 @@ public class HelloWorldClient {
} }
/**
* The main method of this app.
*
* @param args Args representing the port the app will listen on.
* @throws Exception An Exception.
*/
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Options options = new Options(); Options options = new Options();
options.addRequiredOption("p", "port", true, "Port to listen or send event to."); options.addRequiredOption("p", "port", true, "Port to listen or send event to.");

View File

@ -1,5 +1,13 @@
/*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*/
package io.dapr.examples.invoke.grpc; package io.dapr.examples.invoke.grpc;
import static io.dapr.examples.DaprExamplesProtos.SayRequest;
import static io.dapr.examples.DaprExamplesProtos.SayResponse;
import com.google.protobuf.Any; import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.InvalidProtocolBufferException;
import io.dapr.DaprClientGrpc; import io.dapr.DaprClientGrpc;
@ -7,25 +15,23 @@ import io.dapr.DaprClientProtos;
import io.grpc.Server; import io.grpc.Server;
import io.grpc.ServerBuilder; import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver; import io.grpc.stub.StreamObserver;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import java.io.IOException; import java.io.IOException;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Calendar; import java.util.Calendar;
import java.util.TimeZone; import java.util.TimeZone;
import org.apache.commons.cli.CommandLine;
import static io.dapr.examples.DaprExamplesProtos.SayRequest; import org.apache.commons.cli.CommandLineParser;
import static io.dapr.examples.DaprExamplesProtos.SayResponse; import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
/** /**
* 1. Build and install jars: * 1. Build and install jars:
* mvn clean install * mvn clean install
* 2. Run in server mode: * 2. Run in server mode:
* dapr run --app-id hellogrpc --app-port 5000 --protocol grpc -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.invoke.grpc.HelloWorldService -Dexec.args="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5009" * dapr run --app-id hellogrpc --app-port 5000 --protocol grpc \
* -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.invoke.grpc.HelloWorldService \
* -Dexec.args="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5009"
*/ */
public class HelloWorldService { public class HelloWorldService {
@ -52,10 +58,10 @@ public class HelloWorldService {
*/ */
private void start(int port) throws IOException { private void start(int port) throws IOException {
this.server = ServerBuilder this.server = ServerBuilder
.forPort(port) .forPort(port)
.addService(this) .addService(this)
.build() .build()
.start(); .start();
System.out.printf("Server: started listening on port %d\n", port); System.out.printf("Server: started listening on port %d\n", port);
// Now we handle ctrl+c (or any other JVM shutdown) // Now we handle ctrl+c (or any other JVM shutdown)
@ -123,6 +129,11 @@ public class HelloWorldService {
} }
} }
/**
* This is the main method of this app.
* @param args The port to listen on.
* @throws Exception An Exception.
*/
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Options options = new Options(); Options options = new Options();
options.addRequiredOption("p", "port", true, "Port to listen to."); options.addRequiredOption("p", "port", true, "Port to listen to.");

View File

@ -15,7 +15,8 @@ import org.apache.commons.cli.Options;
* 1. Build and install jars: * 1. Build and install jars:
* mvn clean install * mvn clean install
* 2. Run in server mode: * 2. Run in server mode:
* dapr run --app-id invokedemo --app-port 3000 --port 3005 -- mvn exec:java -pl=examples -D exec.mainClass=io.dapr.examples.invoke.http.DemoService -D exec.args="-p 3000" * dapr run --app-id invokedemo --app-port 3000 --port 3005 \
* -- mvn exec:java -pl=examples -D exec.mainClass=io.dapr.examples.invoke.http.DemoService -D exec.args="-p 3000"
*/ */
public class DemoService { public class DemoService {

View File

@ -6,11 +6,6 @@
package io.dapr.examples.invoke.http; package io.dapr.examples.invoke.http;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.text.DateFormat; import java.text.DateFormat;
@ -19,6 +14,12 @@ import java.util.Calendar;
import java.util.Map; import java.util.Map;
import java.util.TimeZone; import java.util.TimeZone;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
/** /**
* SpringBoot Controller to handle input binding. * SpringBoot Controller to handle input binding.
*/ */
@ -35,6 +36,12 @@ public class DemoServiceController {
*/ */
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
/**
* Handles a dapr service invocation endpoint on this app.
* @param body The body of the http message.
* @param headers The headers of the http message.
* @return A message containing the time.
*/
@PostMapping(path = "/say") @PostMapping(path = "/say")
public Mono<String> handleMethod(@RequestBody(required = false) byte[] body, public Mono<String> handleMethod(@RequestBody(required = false) byte[] body,
@RequestHeader Map<String, String> headers) { @RequestHeader Map<String, String> headers) {
@ -49,7 +56,7 @@ public class DemoServiceController {
// Handles the request by printing message. // Handles the request by printing message.
System.out.println( System.out.println(
"Server: " + message + " @ " + utcNowAsString + " and metadata: " + metadataString); "Server: " + message + " @ " + utcNowAsString + " and metadata: " + metadataString);
return utcNowAsString; return utcNowAsString;
} catch (Exception e) { } catch (Exception e) {

View File

@ -7,14 +7,14 @@ package io.dapr.examples.invoke.http;
import io.dapr.client.DaprClient; import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder; import io.dapr.client.DaprClientBuilder;
import io.dapr.serializer.DefaultObjectSerializer;
import io.dapr.client.domain.Verb; import io.dapr.client.domain.Verb;
/** /**
* 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 --port 3006 -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.invoke.http.InvokeClient -Dexec.args="'message one' 'message two'" * dapr run --port 3006 -- mvn exec:java -pl=examples \
* -Dexec.mainClass=io.dapr.examples.invoke.http.InvokeClient -Dexec.args="'message one' 'message two'"
*/ */
public class InvokeClient { public class InvokeClient {
@ -25,6 +25,7 @@ public class InvokeClient {
/** /**
* Starts the invoke client. * Starts the invoke client.
*
* @param args Messages to be sent as request for the invoke API. * @param args Messages to be sent as request for the invoke API.
*/ */
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -16,7 +16,8 @@ import java.util.Collections;
* 1. Build and install jars: * 1. Build and install jars:
* mvn clean install * mvn clean install
* 2. Run the program: * 2. Run the program:
* dapr run --app-id publisher --port 3006 -- mvn exec:java -pl=examples -D exec.mainClass=io.dapr.examples.pubsub.http.Publisher * dapr run --app-id publisher --port 3006 -- \
* mvn exec:java -pl=examples -D exec.mainClass=io.dapr.examples.pubsub.http.Publisher
*/ */
public class Publisher { public class Publisher {
@ -25,6 +26,11 @@ public class Publisher {
//The title of the topic to be used for publishing //The title of the topic to be used for publishing
private static final String TOPIC_NAME = "testingtopic"; private static final String TOPIC_NAME = "testingtopic";
/**
* This is the entry point of the publisher app example.
* @param args Args, unused.
* @throws Exception A startup Exception.
*/
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
//Creating the DaprClient: Using the default builder client produces an HTTP Dapr Client //Creating the DaprClient: Using the default builder client produces an HTTP Dapr Client
DaprClient client = new DaprClientBuilder().build(); DaprClient client = new DaprClientBuilder().build();

View File

@ -16,13 +16,19 @@ import org.apache.commons.cli.Options;
* 1. Build and install jars: * 1. Build and install jars:
* mvn clean install * mvn clean install
* 2. Run the server: * 2. Run the server:
* dapr run --app-id subscriber --app-port 3000 --port 3005 -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.pubsub.http.Subscriber -Dexec.args="-p 3000" * dapr run --app-id subscriber --app-port 3000 --port 3005 -- \
* mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.pubsub.http.Subscriber -Dexec.args="-p 3000"
*/ */
public class Subscriber { public class Subscriber {
/**
* This is the entry point for this example app, which subscribes to a topic.
* @param args The port this app will listen on.
* @throws Exception An Exception on startup.
*/
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Options options = new Options(); Options options = new Options();
options.addRequiredOption("p", "port", true, "Port Dapr will listen to."); options.addRequiredOption("p", "port", true, "The port this app will listen on");
CommandLineParser parser = new DefaultParser(); CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args); CommandLine cmd = parser.parse(options, args);

View File

@ -7,11 +7,15 @@ package io.dapr.examples.pubsub.http;
import io.dapr.client.domain.CloudEvent; import io.dapr.client.domain.CloudEvent;
import io.dapr.serializer.DefaultObjectSerializer; import io.dapr.serializer.DefaultObjectSerializer;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import java.util.Map; import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
/** /**
* SpringBoot Controller to handle input binding. * SpringBoot Controller to handle input binding.
*/ */
@ -21,13 +25,19 @@ public class SubscriberController {
/** /**
* Dapr's default serializer/deserializer. * Dapr's default serializer/deserializer.
*/ */
private static final DefaultObjectSerializer SERIALIZER = new DefaultObjectSerializer (); private static final DefaultObjectSerializer SERIALIZER = new DefaultObjectSerializer();
@GetMapping("/dapr/subscribe") @GetMapping("/dapr/subscribe")
public byte[] daprConfig() throws Exception { public byte[] daprConfig() throws Exception {
return SERIALIZER.serialize(new String[] { "testingtopic" }); return SERIALIZER.serialize(new String[]{"testingtopic"});
} }
/**
* Handles a registered publish endpoint on this app.
* @param body The body of the http message.
* @param headers The headers of the http message.
* @return A message containing the time.
*/
@PostMapping(path = "/testingtopic") @PostMapping(path = "/testingtopic")
public Mono<Void> handleMessage(@RequestBody(required = false) byte[] body, public Mono<Void> handleMessage(@RequestBody(required = false) byte[] body,
@RequestHeader Map<String, String> headers) { @RequestHeader Map<String, String> headers) {

View File

@ -4,7 +4,11 @@ import com.google.protobuf.Any;
import com.google.protobuf.ByteString; import com.google.protobuf.ByteString;
import io.dapr.DaprGrpc; import io.dapr.DaprGrpc;
import io.dapr.DaprGrpc.DaprBlockingStub; import io.dapr.DaprGrpc.DaprBlockingStub;
import io.dapr.DaprProtos.*; import io.dapr.DaprProtos.DeleteStateEnvelope;
import io.dapr.DaprProtos.GetStateEnvelope;
import io.dapr.DaprProtos.GetStateResponseEnvelope;
import io.dapr.DaprProtos.SaveStateEnvelope;
import io.dapr.DaprProtos.StateRequest;
import io.grpc.ManagedChannel; import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder; import io.grpc.ManagedChannelBuilder;
@ -16,9 +20,13 @@ 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 {
/**
* The main method of this app.
* @param args Not used.
*/
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";
@ -26,13 +34,13 @@ public class Example {
{ {
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!");
} }
@ -40,9 +48,9 @@ public class Example {
// Now, read it back. // Now, read it back.
{ {
GetStateEnvelope req = GetStateEnvelope GetStateEnvelope req = GetStateEnvelope
.newBuilder() .newBuilder()
.setKey(key) .setKey(key)
.build(); .build();
GetStateResponseEnvelope response = client.getState(req); GetStateResponseEnvelope response = client.getState(req);
String value = response.getData().getValue().toStringUtf8(); String value = response.getData().getValue().toStringUtf8();
System.out.println("Got: " + value); System.out.println("Got: " + value);
@ -51,9 +59,9 @@ public class Example {
// Then, delete it. // Then, delete it.
{ {
DeleteStateEnvelope req = DeleteStateEnvelope DeleteStateEnvelope req = DeleteStateEnvelope
.newBuilder() .newBuilder()
.setKey(key) .setKey(key)
.build(); .build();
client.deleteState(req); client.deleteState(req);
System.out.println("Deleted!"); System.out.println("Deleted!");
} }

View File

@ -1,60 +1,65 @@
package io.dapr.examples.state.http; package io.dapr.examples.state.http;
import static java.lang.System.out;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.HttpServer;
import io.dapr.client.DaprClient; import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder; import io.dapr.client.DaprClientBuilder;
import io.dapr.serializer.DefaultObjectSerializer;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
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 * <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: * <p>To install jars into your local maven repo:
* mvn clean install * mvn clean install
* <p> *
* To run (after step above): * <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 \
* <p> * -Dexec.mainClass=io.dapr.examples.state.http.OrderManager
* If this class changes, run this before running it again: *
* <p>If this class changes, run this before running it again:
* mvn compile * mvn compile
*/ */
public class OrderManager { public class OrderManager {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
/**
* The main method of this app.
* @param args Unused.
* @throws IOException An exception.
*/
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
int httpPort = 3001; int httpPort = 3001;
HttpServer httpServer = HttpServer.create(new InetSocketAddress(httpPort), 0); HttpServer httpServer = HttpServer.create(new InetSocketAddress(httpPort), 0);
DaprClient daprClient = DaprClient daprClient =
(new DaprClientBuilder()).build(); (new DaprClientBuilder()).build();
httpServer.createContext("/order").setHandler(e -> { httpServer.createContext("/order").setHandler(e -> {
out.println("Fetching order!"); out.println("Fetching order!");
try { try {
byte[] data = daprClient.getState("order", String.class).block().getValue().getBytes(); byte[] data = daprClient.getState("order", String.class).block().getValue().getBytes();
e.getResponseHeaders().set("content-type", "application/json"); e.getResponseHeaders().set("content-type", "application/json");
e.sendResponseHeaders(200, data.length); e.sendResponseHeaders(200, data.length);
e.getResponseBody().write(data); e.getResponseBody().write(data);
e.getResponseBody().close(); e.getResponseBody().close();
} catch (IOException ioerror) { } catch (IOException ioerror) {
out.println(ioerror); out.println(ioerror);
e.sendResponseHeaders(500, ioerror.getMessage().getBytes().length); e.sendResponseHeaders(500, ioerror.getMessage().getBytes().length);
e.getResponseBody().write(ioerror.getMessage().getBytes()); e.getResponseBody().write(ioerror.getMessage().getBytes());
e.getResponseBody().close(); e.getResponseBody().close();
} }
}); });
httpServer.createContext("/neworder").setHandler(e -> { httpServer.createContext("/neworder").setHandler(e -> {
@ -92,13 +97,14 @@ public class OrderManager {
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int len; int len;
try { try {
while ((len = is.read(buffer)) > 0) while ((len = is.read(buffer)) > 0) {
bos.write(buffer, 0, len); bos.write(buffer, 0, len);
}
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
bos.close(); bos.close();
} }
return new String(bos.toByteArray(), Charset.forName("UTF-8")); return new String(bos.toByteArray(), StandardCharsets.UTF_8);
} }
} }

View File

@ -6,7 +6,13 @@
package io.dapr.springboot; package io.dapr.springboot;
import io.dapr.actors.runtime.ActorRuntime; import io.dapr.actors.runtime.ActorRuntime;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
/** /**

View File

@ -127,7 +127,9 @@
<configLocation>checkstyle.xml</configLocation> <configLocation>checkstyle.xml</configLocation>
<encoding>UTF-8</encoding> <encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput> <consoleOutput>true</consoleOutput>
<failsOnError>false</failsOnError> <violationSeverity>warning</violationSeverity>
<failOnViolation>true</failOnViolation>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef> <linkXRef>false</linkXRef>
</configuration> </configuration>
<executions> <executions>

View File

@ -39,7 +39,7 @@ class DaprHttpClient implements DaprClient {
public Mono<byte[]> invokeActorMethod(String actorType, String actorId, String methodName, byte[] jsonPayload) { public Mono<byte[]> invokeActorMethod(String actorType, String actorId, String methodName, byte[] jsonPayload) {
String url = String.format(Constants.ACTOR_METHOD_RELATIVE_URL_FORMAT, actorType, actorId, methodName); String url = String.format(Constants.ACTOR_METHOD_RELATIVE_URL_FORMAT, actorType, actorId, methodName);
Mono<DaprHttp.Response> responseMono = Mono<DaprHttp.Response> responseMono =
this.client.invokeAPI(DaprHttp.HttpMethods.POST.name(), url, null, jsonPayload, null); this.client.invokeApi(DaprHttp.HttpMethods.POST.name(), url, null, jsonPayload, null);
return responseMono.map(r -> r.getBody()); return responseMono.map(r -> r.getBody());
} }

View File

@ -36,7 +36,7 @@ class DaprHttpClient implements DaprClient {
@Override @Override
public Mono<byte[]> getActorState(String actorType, String actorId, String keyName) { public Mono<byte[]> getActorState(String actorType, String actorId, String keyName) {
String url = String.format(Constants.ACTOR_STATE_KEY_RELATIVE_URL_FORMAT, actorType, actorId, keyName); String url = String.format(Constants.ACTOR_STATE_KEY_RELATIVE_URL_FORMAT, actorType, actorId, keyName);
Mono<DaprHttp.Response> responseMono = this.client.invokeAPI(DaprHttp.HttpMethods.GET.name(), url, null, "", null); Mono<DaprHttp.Response> responseMono = this.client.invokeApi(DaprHttp.HttpMethods.GET.name(), url, null, "", null);
return responseMono.map(r -> r.getBody()); return responseMono.map(r -> r.getBody());
} }
@ -46,7 +46,7 @@ class DaprHttpClient implements DaprClient {
@Override @Override
public Mono<Void> saveActorStateTransactionally(String actorType, String actorId, byte[] data) { public Mono<Void> saveActorStateTransactionally(String actorType, String actorId, byte[] data) {
String url = String.format(Constants.ACTOR_STATE_RELATIVE_URL_FORMAT, actorType, actorId); String url = String.format(Constants.ACTOR_STATE_RELATIVE_URL_FORMAT, actorType, actorId);
return this.client.invokeAPI(DaprHttp.HttpMethods.PUT.name(), url, null, data, null).then(); return this.client.invokeApi(DaprHttp.HttpMethods.PUT.name(), url, null, data, null).then();
} }
/** /**
@ -55,7 +55,7 @@ class DaprHttpClient implements DaprClient {
@Override @Override
public Mono<Void> registerActorReminder(String actorType, String actorId, String reminderName, byte[] data) { public Mono<Void> registerActorReminder(String actorType, String actorId, String reminderName, byte[] data) {
String url = String.format(Constants.ACTOR_REMINDER_RELATIVE_URL_FORMAT, actorType, actorId, reminderName); String url = String.format(Constants.ACTOR_REMINDER_RELATIVE_URL_FORMAT, actorType, actorId, reminderName);
return this.client.invokeAPI(DaprHttp.HttpMethods.PUT.name(), url, null, data, null).then(); return this.client.invokeApi(DaprHttp.HttpMethods.PUT.name(), url, null, data, null).then();
} }
/** /**
@ -64,7 +64,7 @@ class DaprHttpClient implements DaprClient {
@Override @Override
public Mono<Void> unregisterActorReminder(String actorType, String actorId, String reminderName) { public Mono<Void> unregisterActorReminder(String actorType, String actorId, String reminderName) {
String url = String.format(Constants.ACTOR_REMINDER_RELATIVE_URL_FORMAT, actorType, actorId, reminderName); String url = String.format(Constants.ACTOR_REMINDER_RELATIVE_URL_FORMAT, actorType, actorId, reminderName);
return this.client.invokeAPI(DaprHttp.HttpMethods.DELETE.name(), url, null, null).then(); return this.client.invokeApi(DaprHttp.HttpMethods.DELETE.name(), url, null, null).then();
} }
/** /**
@ -73,7 +73,7 @@ class DaprHttpClient implements DaprClient {
@Override @Override
public Mono<Void> registerActorTimer(String actorType, String actorId, String timerName, byte[] data) { public Mono<Void> registerActorTimer(String actorType, String actorId, String timerName, byte[] data) {
String url = String.format(Constants.ACTOR_TIMER_RELATIVE_URL_FORMAT, actorType, actorId, timerName); String url = String.format(Constants.ACTOR_TIMER_RELATIVE_URL_FORMAT, actorType, actorId, timerName);
return this.client.invokeAPI(DaprHttp.HttpMethods.PUT.name(), url, null, data, null).then(); return this.client.invokeApi(DaprHttp.HttpMethods.PUT.name(), url, null, data, null).then();
} }
/** /**
@ -82,7 +82,7 @@ class DaprHttpClient implements DaprClient {
@Override @Override
public Mono<Void> unregisterActorTimer(String actorType, String actorId, String timerName) { public Mono<Void> unregisterActorTimer(String actorType, String actorId, String timerName) {
String url = String.format(Constants.ACTOR_TIMER_RELATIVE_URL_FORMAT, actorType, actorId, timerName); String url = String.format(Constants.ACTOR_TIMER_RELATIVE_URL_FORMAT, actorType, actorId, timerName);
return this.client.invokeAPI(DaprHttp.HttpMethods.DELETE.name(), url, null, null).then(); return this.client.invokeApi(DaprHttp.HttpMethods.DELETE.name(), url, null, null).then();
} }
} }

View File

@ -137,7 +137,7 @@ class DaprStateAsyncProvider {
generator.writeObjectFieldStart("request"); generator.writeObjectFieldStart("request");
generator.writeStringField("key", stateChange.getStateName()); generator.writeStringField("key", stateChange.getStateName());
if ((stateChange.getChangeKind() == ActorStateChangeKind.UPDATE) if ((stateChange.getChangeKind() == ActorStateChangeKind.UPDATE)
|| (stateChange.getChangeKind() == ActorStateChangeKind.ADD)) { || (stateChange.getChangeKind() == ActorStateChangeKind.ADD)) {
byte[] data = this.stateSerializer.serialize(stateChange.getValue()); byte[] data = this.stateSerializer.serialize(stateChange.getValue());
if (data != null) { if (data != null) {
if (this.isStateString) { if (this.isStateString) {

View File

@ -67,8 +67,8 @@ public class ObjectSerializer extends io.dapr.client.ObjectSerializer {
try (ByteArrayOutputStream writer = new ByteArrayOutputStream()) { try (ByteArrayOutputStream writer = new ByteArrayOutputStream()) {
JsonGenerator generator = JSON_FACTORY.createGenerator(writer); JsonGenerator generator = JSON_FACTORY.createGenerator(writer);
generator.writeStartObject(); generator.writeStartObject();
generator.writeStringField("dueTime", DurationUtils.ConvertDurationToDaprFormat(timer.getDueTime())); generator.writeStringField("dueTime", DurationUtils.convertDurationToDaprFormat(timer.getDueTime()));
generator.writeStringField("period", DurationUtils.ConvertDurationToDaprFormat(timer.getPeriod())); generator.writeStringField("period", DurationUtils.convertDurationToDaprFormat(timer.getPeriod()));
generator.writeStringField("callback", timer.getCallback()); generator.writeStringField("callback", timer.getCallback());
if (timer.getState() != null) { if (timer.getState() != null) {
generator.writeBinaryField("data", this.serialize(timer.getState())); generator.writeBinaryField("data", this.serialize(timer.getState()));
@ -91,8 +91,8 @@ public class ObjectSerializer extends io.dapr.client.ObjectSerializer {
try (ByteArrayOutputStream writer = new ByteArrayOutputStream()) { try (ByteArrayOutputStream writer = new ByteArrayOutputStream()) {
JsonGenerator generator = JSON_FACTORY.createGenerator(writer); JsonGenerator generator = JSON_FACTORY.createGenerator(writer);
generator.writeStartObject(); generator.writeStartObject();
generator.writeStringField("dueTime", DurationUtils.ConvertDurationToDaprFormat(reminder.getDueTime())); generator.writeStringField("dueTime", DurationUtils.convertDurationToDaprFormat(reminder.getDueTime()));
generator.writeStringField("period", DurationUtils.ConvertDurationToDaprFormat(reminder.getPeriod())); generator.writeStringField("period", DurationUtils.convertDurationToDaprFormat(reminder.getPeriod()));
if (reminder.getData() != null) { if (reminder.getData() != null) {
generator.writeBinaryField("data", reminder.getData()); generator.writeBinaryField("data", reminder.getData());
} }
@ -121,15 +121,15 @@ public class ObjectSerializer extends io.dapr.client.ObjectSerializer {
generator.writeEndArray(); generator.writeEndArray();
if (config.getActorIdleTimeout() != null) { if (config.getActorIdleTimeout() != null) {
generator.writeStringField("actorIdleTimeout", generator.writeStringField("actorIdleTimeout",
DurationUtils.ConvertDurationToDaprFormat(config.getActorIdleTimeout())); DurationUtils.convertDurationToDaprFormat(config.getActorIdleTimeout()));
} }
if (config.getActorScanInterval() != null) { if (config.getActorScanInterval() != null) {
generator.writeStringField("actorScanInterval", generator.writeStringField("actorScanInterval",
DurationUtils.ConvertDurationToDaprFormat(config.getActorScanInterval())); DurationUtils.convertDurationToDaprFormat(config.getActorScanInterval()));
} }
if (config.getDrainOngoingCallTimeout() != null) { if (config.getDrainOngoingCallTimeout() != null) {
generator.writeStringField("drainOngoingCallTimeout", generator.writeStringField("drainOngoingCallTimeout",
DurationUtils.ConvertDurationToDaprFormat(config.getDrainOngoingCallTimeout())); DurationUtils.convertDurationToDaprFormat(config.getDrainOngoingCallTimeout()));
} }
if (config.getDrainBalancedActors() != null) { if (config.getDrainBalancedActors() != null) {
generator.writeBooleanField("drainBalancedActors", config.getDrainBalancedActors()); generator.writeBooleanField("drainBalancedActors", config.getDrainBalancedActors());
@ -214,8 +214,8 @@ public class ObjectSerializer extends io.dapr.client.ObjectSerializer {
} }
JsonNode node = OBJECT_MAPPER.readTree(value); JsonNode node = OBJECT_MAPPER.readTree(value);
Duration dueTime = DurationUtils.ConvertDurationFromDaprFormat(node.get("dueTime").asText()); Duration dueTime = DurationUtils.convertDurationFromDaprFormat(node.get("dueTime").asText());
Duration period = DurationUtils.ConvertDurationFromDaprFormat(node.get("period").asText()); Duration period = DurationUtils.convertDurationFromDaprFormat(node.get("period").asText());
byte[] data = node.get("data") != null ? node.get("data").binaryValue() : null; byte[] data = node.get("data") != null ? node.get("data").binaryValue() : null;
return new ActorReminderParams(data, dueTime, period); return new ActorReminderParams(data, dueTime, period);

View File

@ -51,7 +51,7 @@ public class ActorTurnBasedConcurrencyIT extends BaseIT {
System.out.println("Invoking during cleanup"); System.out.println("Invoking during cleanup");
try { try {
client.invokeAPI(DaprHttp.HttpMethods.DELETE.name(), url, null, null).block(); client.invokeApi(DaprHttp.HttpMethods.DELETE.name(), url, null, null).block();
} catch(Exception e) { } catch(Exception e) {
// informational only // informational only
System.out.println("Caught " + e.toString()); System.out.println("Caught " + e.toString());

View File

@ -2,15 +2,15 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.client; package io.dapr.client;
import io.dapr.client.domain.State; import io.dapr.client.domain.State;
import io.dapr.client.domain.StateOptions; import io.dapr.client.domain.StateOptions;
import io.dapr.client.domain.Verb; import io.dapr.client.domain.Verb;
import reactor.core.publisher.Mono;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import reactor.core.publisher.Mono;
/** /**
* Generic Client Adapter to be used regardless of the GRPC or the HTTP Client implementation required. * Generic Client Adapter to be used regardless of the GRPC or the HTTP Client implementation required.
@ -53,7 +53,8 @@ public interface DaprClient {
* @param <R> The Type of the request, use byte[] to skip serialization. * @param <R> The Type of the request, use byte[] to skip serialization.
* @return A Mono Plan of type clazz. * @return A Mono Plan of type clazz.
*/ */
<T, R> Mono<T> invokeService(Verb verb, String appId, String method, R request, Map<String, String> metadata, Class<T> clazz); <T, R> Mono<T> invokeService(
Verb verb, String appId, String method, R request, Map<String, String> metadata, Class<T> clazz);
/** /**
* Invoke a service without input, using serialization for response. * Invoke a service without input, using serialization for response.

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.client; package io.dapr.client;
import io.dapr.DaprGrpc; import io.dapr.DaprGrpc;
@ -19,108 +20,106 @@ import okhttp3.OkHttpClient;
*/ */
public class DaprClientBuilder { public class DaprClientBuilder {
/** /**
* Determine if this builder will create GRPC clients instead of HTTP clients. * Determine if this builder will create GRPC clients instead of HTTP clients.
*/ */
private final boolean useGRPC; private final boolean useGrpc;
/** /**
* Serializer used for request and response objects in DaprClient. * Serializer used for request and response objects in DaprClient.
*/ */
private DaprObjectSerializer objectSerializer; private DaprObjectSerializer objectSerializer;
/** /**
* Serializer used for state objects in DaprClient. * Serializer used for state objects in DaprClient.
*/ */
private DaprObjectSerializer stateSerializer; private DaprObjectSerializer stateSerializer;
/** /**
* Creates a constructor for DaprClient. * Creates a constructor for DaprClient.
* *
* {@link DefaultObjectSerializer} is used for object and state serializers by defaul but is not recommended * {@link DefaultObjectSerializer} is used for object and state serializers by defaul but is not recommended
* for production scenarios. * for production scenarios.
*/ */
public DaprClientBuilder() { public DaprClientBuilder() {
this.objectSerializer = new DefaultObjectSerializer(); this.objectSerializer = new DefaultObjectSerializer();
this.stateSerializer = new DefaultObjectSerializer(); this.stateSerializer = new DefaultObjectSerializer();
this.useGRPC = Properties.USE_GRPC.get(); this.useGrpc = Properties.USE_GRPC.get();
}
/**
* Sets the serializer for objects to be sent and received from Dapr.
* See {@link DefaultObjectSerializer} as possible serializer for non-production scenarios.
*
* @param objectSerializer Serializer for objects to be sent and received from Dapr.
* @return This instance.
*/
public DaprClientBuilder withObjectSerializer(DaprObjectSerializer objectSerializer) {
if (objectSerializer == null) {
throw new IllegalArgumentException("Object serializer is required");
} }
/** this.objectSerializer = objectSerializer;
* Sets the serializer for objects to be sent and received from Dapr. return this;
* }
* See {@link DefaultObjectSerializer} as possible serializer for non-production scenarios.
*
* @param objectSerializer Serializer for objects to be sent and received from Dapr.
* @return This instance.
*/
public DaprClientBuilder withObjectSerializer(DaprObjectSerializer objectSerializer) {
if (objectSerializer == null) {
throw new IllegalArgumentException("Object serializer is required");
}
this.objectSerializer = objectSerializer; /**
return this; * Sets the serializer for objects to be persisted.
* See {@link DefaultObjectSerializer} as possible serializer for non-production scenarios.
*
* @param stateSerializer Serializer for objects to be persisted.
* @return This instance.
*/
public DaprClientBuilder withStateSerializer(DaprObjectSerializer stateSerializer) {
if (stateSerializer == null) {
throw new IllegalArgumentException("State serializer is required");
} }
/** this.stateSerializer = stateSerializer;
* Sets the serializer for objects to be persisted. return this;
* }
* See {@link DefaultObjectSerializer} as possible serializer for non-production scenarios.
*
* @param stateSerializer Serializer for objects to be persisted.
* @return This instance.
*/
public DaprClientBuilder withStateSerializer(DaprObjectSerializer stateSerializer) {
if (stateSerializer == null) {
throw new IllegalArgumentException("State serializer is required");
}
this.stateSerializer = stateSerializer; /**
return this; * Build an instance of the Client based on the provided setup.
*
* @return an instance of the setup Client
* @throws java.lang.IllegalStateException if any required field is missing
*/
public DaprClient build() {
if (this.useGrpc) {
return buildDaprClientGrpc();
} }
/** return buildDaprClientHttp();
* Build an instance of the Client based on the provided setup. }
*
* @return an instance of the setup Client
* @throws java.lang.IllegalStateException if any required field is missing
*/
public DaprClient build() {
if (this.useGRPC) {
return buildDaprClientGrpc();
}
return buildDaprClientHttp(); /**
* Creates an instance of the GPRC Client.
*
* @return the GRPC Client.
* @throws java.lang.IllegalStateException if either host is missing or if port is missing or a negative number.
*/
private DaprClient buildDaprClientGrpc() {
int port = Properties.GRPC_PORT.get();
if (port <= 0) {
throw new IllegalStateException("Invalid port.");
} }
ManagedChannel channel = ManagedChannelBuilder.forAddress(Constants.DEFAULT_HOSTNAME, port).usePlaintext().build();
return new DaprClientGrpcAdapter(DaprGrpc.newFutureStub(channel), this.objectSerializer, this.stateSerializer);
}
/** /**
* Creates an instance of the GPRC Client. * Creates and instance of DaprClient over HTTP.
* *
* @return the GRPC Client. * @return DaprClient over HTTP.
* @throws java.lang.IllegalStateException if either host is missing or if port is missing or a negative number. */
*/ private DaprClient buildDaprClientHttp() {
private DaprClient buildDaprClientGrpc() { int port = Properties.HTTP_PORT.get();
int port = Properties.GRPC_PORT.get(); if (port <= 0) {
if (port <= 0) { throw new IllegalStateException("Invalid port.");
throw new IllegalStateException("Invalid port.");
}
ManagedChannel channel = ManagedChannelBuilder.forAddress(Constants.DEFAULT_HOSTNAME, port).usePlaintext().build();
return new DaprClientGrpcAdapter(DaprGrpc.newFutureStub(channel), this.objectSerializer, this.stateSerializer);
}
/**
* Creates and instance of DaprClient over HTTP.
*
* @return DaprClient over HTTP.
*/
private DaprClient buildDaprClientHttp() {
int port = Properties.HTTP_PORT.get();
if (port <= 0) {
throw new IllegalStateException("Invalid port.");
}
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
DaprHttp daprHttp = new DaprHttp(port, okHttpClient);
return new DaprClientHttpAdapter(daprHttp, this.objectSerializer, this.stateSerializer);
} }
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
DaprHttp daprHttp = new DaprHttp(port, okHttpClient);
return new DaprClientHttpAdapter(daprHttp, this.objectSerializer, this.stateSerializer);
}
} }

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.client; package io.dapr.client;
import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListenableFuture;
@ -15,13 +16,14 @@ import io.dapr.client.domain.State;
import io.dapr.client.domain.StateOptions; import io.dapr.client.domain.StateOptions;
import io.dapr.client.domain.Verb; import io.dapr.client.domain.Verb;
import io.dapr.serializer.DaprObjectSerializer; import io.dapr.serializer.DaprObjectSerializer;
import reactor.core.publisher.Mono;
import java.io.IOException; import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import reactor.core.publisher.Mono;
/** /**
* An adapter for the GRPC Client. * An adapter for the GRPC Client.
* *
@ -31,7 +33,7 @@ import java.util.Map;
public class DaprClientGrpcAdapter implements DaprClient { public class DaprClientGrpcAdapter implements DaprClient {
/** /**
* The GRPC client to be used * The GRPC client to be used.
* *
* @see io.dapr.DaprGrpc.DaprFutureStub * @see io.dapr.DaprGrpc.DaprFutureStub
*/ */
@ -56,9 +58,9 @@ public class DaprClientGrpcAdapter implements DaprClient {
* @see DaprClientBuilder * @see DaprClientBuilder
*/ */
DaprClientGrpcAdapter( DaprClientGrpcAdapter(
DaprGrpc.DaprFutureStub futureClient, DaprGrpc.DaprFutureStub futureClient,
DaprObjectSerializer objectSerializer, DaprObjectSerializer objectSerializer,
DaprObjectSerializer stateSerializer) { DaprObjectSerializer stateSerializer) {
this.client = futureClient; this.client = futureClient;
this.objectSerializer = objectSerializer; this.objectSerializer = objectSerializer;
this.stateSerializer = stateSerializer; this.stateSerializer = stateSerializer;
@ -99,7 +101,13 @@ public class DaprClientGrpcAdapter implements DaprClient {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public <T, R> Mono<T> invokeService(Verb verb, String appId, String method, R request, Map<String, String> metadata, Class<T> clazz) { public <T, R> Mono<T> invokeService(
Verb verb,
String appId,
String method,
R request,
Map<String, String> metadata,
Class<T> clazz) {
try { try {
DaprProtos.InvokeServiceEnvelope envelope = buildInvokeServiceEnvelope(verb.toString(), appId, method, request); DaprProtos.InvokeServiceEnvelope envelope = buildInvokeServiceEnvelope(verb.toString(), appId, method, request);
return Mono.fromCallable(() -> { return Mono.fromCallable(() -> {
@ -116,7 +124,12 @@ public class DaprClientGrpcAdapter implements DaprClient {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public <T> Mono<T> invokeService(Verb verb, String appId, String method, Map<String, String> metadata, Class<T> clazz) { public <T> Mono<T> invokeService(
Verb verb,
String appId,
String method,
Map<String, String> metadata,
Class<T> clazz) {
return this.invokeService(verb, appId, method, null, null, clazz); return this.invokeService(verb, appId, method, null, null, clazz);
} }
@ -124,7 +137,12 @@ public class DaprClientGrpcAdapter implements DaprClient {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public <R> Mono<Void> invokeService(Verb verb, String appId, String method, R request, Map<String, String> metadata) { public <R> Mono<Void> invokeService(
Verb verb,
String appId,
String method,
R request,
Map<String, String> metadata) {
return this.invokeService(verb, appId, method, request, metadata, byte[].class).then(); return this.invokeService(verb, appId, method, request, metadata, byte[].class).then();
} }
@ -140,7 +158,12 @@ public class DaprClientGrpcAdapter implements DaprClient {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Mono<byte[]> invokeService(Verb verb, String appId, String method, byte[] request, Map<String, String> metadata) { public Mono<byte[]> invokeService(
Verb verb,
String appId,
String method,
byte[] request,
Map<String, String> metadata) {
return this.invokeService(verb, appId, method, request, metadata, byte[].class); return this.invokeService(verb, appId, method, request, metadata, byte[].class);
} }
@ -204,16 +227,17 @@ public class DaprClientGrpcAdapter implements DaprClient {
return null; return null;
} }
return buildStateKeyValue(response, key, options, clazz); return buildStateKeyValue(response, key, options, clazz);
}); } catch (Exception ex) { });
} catch (Exception ex) {
return Mono.error(ex); return Mono.error(ex);
} }
} }
private <T> State<T> buildStateKeyValue( private <T> State<T> buildStateKeyValue(
DaprProtos.GetStateResponseEnvelope response, DaprProtos.GetStateResponseEnvelope response,
String requestedKey, String requestedKey,
StateOptions stateOptions, StateOptions stateOptions,
Class<T> clazz) throws IOException { Class<T> clazz) throws IOException {
ByteString payload = response.getData().getValue(); ByteString payload = response.getData().getValue();
byte[] data = payload == null ? null : payload.toByteArray(); byte[] data = payload == null ? null : payload.toByteArray();
T value = stateSerializer.deserialize(data, clazz); T value = stateSerializer.deserialize(data, clazz);
@ -291,7 +315,7 @@ public class DaprClientGrpcAdapter implements DaprClient {
optionBuilder.setRetryPolicy(retryPolicyBuilder.build()); optionBuilder.setRetryPolicy(retryPolicyBuilder.build());
} }
} }
if(optionBuilder != null) { if (optionBuilder != null) {
stateBuilder.setOptions(optionBuilder.build()); stateBuilder.setOptions(optionBuilder.build());
} }
return stateBuilder; return stateBuilder;
@ -361,9 +385,9 @@ public class DaprClientGrpcAdapter implements DaprClient {
} }
} }
DaprProtos.DeleteStateEnvelope.Builder builder = DaprProtos.DeleteStateEnvelope.newBuilder() DaprProtos.DeleteStateEnvelope.Builder builder = DaprProtos.DeleteStateEnvelope.newBuilder()
.setKey(key); .setKey(key);
if(etag != null) { if (etag != null) {
builder.setEtag(etag); builder.setEtag(etag);
} }
if (optionBuilder != null) { if (optionBuilder != null) {

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.client; package io.dapr.client;
import io.dapr.client.domain.State; import io.dapr.client.domain.State;
@ -11,10 +12,16 @@ import io.dapr.serializer.DaprObjectSerializer;
import io.dapr.serializer.DefaultObjectSerializer; import io.dapr.serializer.DefaultObjectSerializer;
import io.dapr.serializer.StringContentType; import io.dapr.serializer.StringContentType;
import io.dapr.utils.Constants; import io.dapr.utils.Constants;
import reactor.core.publisher.Mono;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import reactor.core.publisher.Mono;
/** /**
* An adapter for the HTTP Client. * An adapter for the HTTP Client.
@ -30,7 +37,7 @@ public class DaprClientHttpAdapter implements DaprClient {
private static final ObjectSerializer INTERNAL_SERIALIZER = new ObjectSerializer(); private static final ObjectSerializer INTERNAL_SERIALIZER = new ObjectSerializer();
/** /**
* The HTTP client to be used * The HTTP client to be used.
* *
* @see io.dapr.client.DaprHttp * @see io.dapr.client.DaprHttp
*/ */
@ -98,7 +105,7 @@ public class DaprClientHttpAdapter implements DaprClient {
byte[] serializedEvent = objectSerializer.serialize(event); byte[] serializedEvent = objectSerializer.serialize(event);
StringBuilder url = new StringBuilder(Constants.PUBLISH_PATH).append("/").append(topic); StringBuilder url = new StringBuilder(Constants.PUBLISH_PATH).append("/").append(topic);
return this.client.invokeAPI( return this.client.invokeApi(
DaprHttp.HttpMethods.POST.name(), url.toString(), null, serializedEvent, metadata).then(); DaprHttp.HttpMethods.POST.name(), url.toString(), null, serializedEvent, metadata).then();
} catch (Exception ex) { } catch (Exception ex) {
return Mono.error(ex); return Mono.error(ex);
@ -109,7 +116,8 @@ public class DaprClientHttpAdapter implements DaprClient {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public <T, R> Mono<T> invokeService(Verb verb, String appId, String method, R request, Map<String, String> metadata, Class<T> clazz) { public <T, R> Mono<T> invokeService(
Verb verb, String appId, String method, R request, Map<String, String> metadata, Class<T> clazz) {
try { try {
if (verb == null) { if (verb == null) {
throw new IllegalArgumentException("Verb cannot be null."); throw new IllegalArgumentException("Verb cannot be null.");
@ -123,19 +131,19 @@ public class DaprClientHttpAdapter implements DaprClient {
} }
String path = String.format("%s/%s/method/%s", Constants.INVOKE_PATH, appId, method); String path = String.format("%s/%s/method/%s", Constants.INVOKE_PATH, appId, method);
byte[] serializedRequestBody = objectSerializer.serialize(request); byte[] serializedRequestBody = objectSerializer.serialize(request);
Mono<DaprHttp.Response> response = this.client.invokeAPI(httMethod, path, null, serializedRequestBody, metadata); Mono<DaprHttp.Response> response = this.client.invokeApi(httMethod, path, null, serializedRequestBody, metadata);
return response.flatMap(r -> { return response.flatMap(r -> {
try { try {
T object = objectSerializer.deserialize(r.getBody(), clazz); T object = objectSerializer.deserialize(r.getBody(), clazz);
if (object == null) { if (object == null) {
return Mono.empty(); return Mono.empty();
} }
return Mono.just(object); return Mono.just(object);
} catch (Exception ex) { } catch (Exception ex) {
return Mono.error(ex); return Mono.error(ex);
} }
}); });
} catch (Exception ex) { } catch (Exception ex) {
return Mono.error(ex); return Mono.error(ex);
} }
@ -145,7 +153,8 @@ public class DaprClientHttpAdapter implements DaprClient {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public <T> Mono<T> invokeService(Verb verb, String appId, String method, Map<String, String> metadata, Class<T> clazz) { public <T> Mono<T> invokeService(
Verb verb, String appId, String method, Map<String, String> metadata, Class<T> clazz) {
return this.invokeService(verb, appId, method, null, null, clazz); return this.invokeService(verb, appId, method, null, null, clazz);
} }
@ -153,7 +162,8 @@ public class DaprClientHttpAdapter implements DaprClient {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public <R> Mono<Void> invokeService(Verb verb, String appId, String method, R request, Map<String, String> metadata) { public <R> Mono<Void> invokeService(
Verb verb, String appId, String method, R request, Map<String, String> metadata) {
return this.invokeService(verb, appId, method, request, metadata, byte[].class).then(); return this.invokeService(verb, appId, method, request, metadata, byte[].class).then();
} }
@ -161,7 +171,8 @@ public class DaprClientHttpAdapter implements DaprClient {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Mono<Void> invokeService(Verb verb, String appId, String method, Map<String, String> metadata) { public Mono<Void> invokeService(
Verb verb, String appId, String method, Map<String, String> metadata) {
return this.invokeService(verb, appId, method, null, metadata, byte[].class).then(); return this.invokeService(verb, appId, method, null, metadata, byte[].class).then();
} }
@ -169,7 +180,8 @@ public class DaprClientHttpAdapter implements DaprClient {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Mono<byte[]> invokeService(Verb verb, String appId, String method, byte[] request, Map<String, String> metadata) { public Mono<byte[]> invokeService(
Verb verb, String appId, String method, byte[] request, Map<String, String> metadata) {
return this.invokeService(verb, appId, method, request, metadata, byte[].class); return this.invokeService(verb, appId, method, request, metadata, byte[].class);
} }
@ -188,7 +200,7 @@ public class DaprClientHttpAdapter implements DaprClient {
StringBuilder url = new StringBuilder(Constants.BINDING_PATH).append("/").append(name); StringBuilder url = new StringBuilder(Constants.BINDING_PATH).append("/").append(name);
return this.client return this.client
.invokeAPI( .invokeApi(
DaprHttp.HttpMethods.POST.name(), DaprHttp.HttpMethods.POST.name(),
url.toString(), url.toString(),
null, null,
@ -231,11 +243,14 @@ public class DaprClientHttpAdapter implements DaprClient {
} }
StringBuilder url = new StringBuilder(Constants.STATE_PATH) StringBuilder url = new StringBuilder(Constants.STATE_PATH)
.append("/") .append("/")
.append(key); .append(key);
Map<String, String> urlParameters = Optional.ofNullable(options).map(o -> o.getStateOptionsAsMap() ).orElse(new HashMap<>());; Map<String, String> urlParameters = Optional.ofNullable(options)
.map(o -> o.getStateOptionsAsMap())
.orElse(new HashMap<>());
return this.client return this.client
.invokeAPI(DaprHttp.HttpMethods.GET.name(), url.toString(), urlParameters, headers) .invokeApi(DaprHttp.HttpMethods.GET.name(), url.toString(), urlParameters, headers)
.flatMap(s -> { .flatMap(s -> {
try { try {
return Mono.just(buildStateKeyValue(s, key, options, clazz)); return Mono.just(buildStateKeyValue(s, key, options, clazz));
@ -272,14 +287,14 @@ public class DaprClientHttpAdapter implements DaprClient {
byte[] data = this.stateSerializer.serialize(state.getValue()); byte[] data = this.stateSerializer.serialize(state.getValue());
if (this.isStateString) { if (this.isStateString) {
internalStateObjects.add( internalStateObjects.add(
new State<>(data == null ? null : new String(data), state.getKey(), state.getEtag(), state.getOptions())); new State<>(data == null ? null : new String(data), state.getKey(), state.getEtag(), state.getOptions()));
} else { } else {
internalStateObjects.add(new State<>(data, state.getKey(), state.getEtag(), state.getOptions())); internalStateObjects.add(new State<>(data, state.getKey(), state.getEtag(), state.getOptions()));
} }
} }
byte[] serializedStateBody = INTERNAL_SERIALIZER.serialize(states); byte[] serializedStateBody = INTERNAL_SERIALIZER.serialize(states);
return this.client.invokeAPI( return this.client.invokeApi(
DaprHttp.HttpMethods.POST.name(), url, null, serializedStateBody, headers).then(); DaprHttp.HttpMethods.POST.name(), url, null, serializedStateBody, headers).then();
} catch (Exception ex) { } catch (Exception ex) {
return Mono.error(ex); return Mono.error(ex);
} }
@ -299,7 +314,7 @@ public class DaprClientHttpAdapter implements DaprClient {
@Override @Override
public Mono<Void> saveState(String key, String etag, Object value, StateOptions options) { public Mono<Void> saveState(String key, String etag, Object value, StateOptions options) {
return Mono.fromSupplier(() -> new State<>(value, key, etag, options)) return Mono.fromSupplier(() -> new State<>(value, key, etag, options))
.flatMap(state -> saveStates(Arrays.asList(state))); .flatMap(state -> saveStates(Arrays.asList(state)));
} }
/** /**
@ -324,25 +339,28 @@ public class DaprClientHttpAdapter implements DaprClient {
headers.put(Constants.HEADER_HTTP_ETAG_ID, etag); headers.put(Constants.HEADER_HTTP_ETAG_ID, etag);
} }
String url = Constants.STATE_PATH + "/" + key; String url = Constants.STATE_PATH + "/" + key;
Map<String, String> urlParameters = Optional.ofNullable(options).map(stateOptions -> stateOptions.getStateOptionsAsMap()).orElse( new HashMap<>());; Map<String, String> urlParameters = Optional.ofNullable(options)
return this.client.invokeAPI(DaprHttp.HttpMethods.DELETE.name(), url, urlParameters, headers).then(); .map(stateOptions -> stateOptions.getStateOptionsAsMap())
.orElse(new HashMap<>());
return this.client.invokeApi(DaprHttp.HttpMethods.DELETE.name(), url, urlParameters, headers).then();
} catch (Exception ex) { } catch (Exception ex) {
return Mono.error(ex); return Mono.error(ex);
} }
} }
/** /**
* Builds a State object based on the Response * Builds a State object based on the Response.
* *
* @param response The response of the HTTP Call * @param response The response of the HTTP Call
* @param requestedKey The Key Requested. * @param requestedKey The Key Requested.
* @param clazz The Class of the Value of the state * @param clazz The Class of the Value of the state
* @param <T> The Type of the Value of the state * @param <T> The Type of the Value of the state
* @return A StateKeyValue instance * @return A StateKeyValue instance
* @throws IOException If there's a issue deserialzing the response. * @throws IOException If there's a issue deserialzing the response.
*/ */
private <T> State<T> buildStateKeyValue( private <T> State<T> buildStateKeyValue(
DaprHttp.Response response, String requestedKey, StateOptions stateOptions, Class<T> clazz) throws IOException { DaprHttp.Response response, String requestedKey, StateOptions stateOptions, Class<T> clazz) throws IOException {
// The state is in the body directly, so we use the state serializer here. // The state is in the body directly, so we use the state serializer here.
T value = stateSerializer.deserialize(response.getBody(), clazz); T value = stateSerializer.deserialize(response.getBody(), clazz);
String key = requestedKey; String key = requestedKey;

View File

@ -2,31 +2,52 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.client; package io.dapr.client;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import io.dapr.exceptions.DaprError; import io.dapr.exceptions.DaprError;
import io.dapr.exceptions.DaprException; import io.dapr.exceptions.DaprException;
import io.dapr.utils.Constants; import io.dapr.utils.Constants;
import okhttp3.*;
import reactor.core.publisher.Mono;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import reactor.core.publisher.Mono;
public class DaprHttp { public class DaprHttp {
/** /**
* HTTP Methods supported. * HTTP Methods supported.
*/ */
public enum HttpMethods {GET, PUT, POST, DELETE;} public enum HttpMethods {
GET,
PUT,
POST,
DELETE
}
public static class Response { public static class Response {
private byte[] body; private byte[] body;
private Map<String, String> headers; private Map<String, String> headers;
private int statusCode; private int statusCode;
/**
* Represents an http response.
* @param body The body of the http response.
* @param headers The headers of the http response.
* @param statusCode The status code of the http response.
*/
public Response(byte[] body, Map<String, String> headers, int statusCode) { public Response(byte[] body, Map<String, String> headers, int statusCode) {
this.body = body; this.body = body;
this.headers = headers; this.headers = headers;
@ -92,52 +113,60 @@ public class DaprHttp {
/** /**
* Invokes an API asynchronously without payload that returns a text payload. * Invokes an API asynchronously without payload that returns a text payload.
* *
* @param method HTTP method. * @param method HTTP method.
* @param urlString url as String. * @param urlString url as String.
* @param urlParameters URL parameters * @param urlParameters URL parameters
* @param headers HTTP headers. * @param headers HTTP headers.
* @return Asynchronous text * @return Asynchronous text
*/ */
public Mono<Response> invokeAPI(String method, String urlString, Map<String, String> urlParameters, Map<String, String> headers) { public Mono<Response> invokeApi(
return this.invokeAPI(method, urlString, urlParameters, (byte[]) null, headers); String method, String urlString, Map<String, String> urlParameters, Map<String, String> headers) {
return this.invokeApi(method, urlString, urlParameters, (byte[]) null, headers);
} }
/** /**
* Invokes an API asynchronously that returns a text payload. * Invokes an API asynchronously that returns a text payload.
* *
* @param method HTTP method. * @param method HTTP method.
* @param urlString url as String. * @param urlString url as String.
* @param urlParameters Parameters in the URL * @param urlParameters Parameters in the URL
* @param content payload to be posted. * @param content payload to be posted.
* @param headers HTTP headers. * @param headers HTTP headers.
* @return Asynchronous response * @return Asynchronous response
*/ */
public Mono<Response> invokeAPI(String method, String urlString, Map<String, String> urlParameters, String content, Map<String, String> headers) { public Mono<Response> invokeApi(
return this.invokeAPI(method, urlString, urlParameters, content == null ? EMPTY_BYTES : content.getBytes(StandardCharsets.UTF_8), headers); String method, String urlString, Map<String, String> urlParameters, String content, Map<String, String> headers) {
return this.invokeApi(
method, urlString, urlParameters, content == null
? EMPTY_BYTES
: content.getBytes(StandardCharsets.UTF_8), headers);
} }
/** /**
* Invokes an API asynchronously that returns a text payload. * Invokes an API asynchronously that returns a text payload.
* *
* @param method HTTP method. * @param method HTTP method.
* @param urlString url as String. * @param urlString url as String.
* @param urlParameters Parameters in the URL * @param urlParameters Parameters in the URL
* @param content payload to be posted. * @param content payload to be posted.
* @param headers HTTP headers. * @param headers HTTP headers.
* @return Asynchronous response * @return Asynchronous response
*/ */
public Mono<Response> invokeAPI(String method, String urlString, Map<String, String> urlParameters, byte[] content, Map<String, String> headers) { public Mono<Response> invokeApi(
String method, String urlString, Map<String, String> urlParameters, byte[] content, Map<String, String> headers) {
return Mono.fromCallable( return Mono.fromCallable(
() -> { () -> {
try { try {
String requestId = UUID.randomUUID().toString(); final String requestId = UUID.randomUUID().toString();
RequestBody body = REQUEST_BODY_EMPTY_JSON; RequestBody body = REQUEST_BODY_EMPTY_JSON;
String contentType = headers != null ? headers.get("content-type") : null; String contentType = headers != null ? headers.get("content-type") : null;
MediaType mediaType = contentType == null ? MEDIA_TYPE_APPLICATION_JSON : MediaType.get(contentType); MediaType mediaType = contentType == null ? MEDIA_TYPE_APPLICATION_JSON : MediaType.get(contentType);
if (content == null) { if (content == null) {
body = mediaType.equals(MEDIA_TYPE_APPLICATION_JSON) ? body = mediaType.equals(MEDIA_TYPE_APPLICATION_JSON)
REQUEST_BODY_EMPTY_JSON : RequestBody.Companion.create(new byte[0], mediaType); ? REQUEST_BODY_EMPTY_JSON
: RequestBody.Companion.create(new byte[0], mediaType);
} else { } else {
body = RequestBody.Companion.create(content, mediaType); body = RequestBody.Companion.create(content, mediaType);
} }

View File

@ -2,58 +2,58 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.client; package io.dapr.client;
import io.dapr.utils.Properties; import io.dapr.utils.Properties;
import okhttp3.OkHttpClient;
import java.time.Duration; import java.time.Duration;
import okhttp3.OkHttpClient;
/** /**
* A builder for the DaprHttp. * A builder for the DaprHttp.
*/ */
public class DaprHttpBuilder { public class DaprHttpBuilder {
/** /**
* Read timeout for http calls. * Read timeout for http calls.
*/ */
private static final Duration DEFAULT_READ_TIMEOUT = Duration.ofSeconds(60); private static final Duration DEFAULT_READ_TIMEOUT = Duration.ofSeconds(60);
/** /**
* Read timeout used to build object. * Read timeout used to build object.
*/ */
private Duration readTimeout = DEFAULT_READ_TIMEOUT; private Duration readTimeout = DEFAULT_READ_TIMEOUT;
/** /**
* Sets the read timeout duration for the instance to be built. * Sets the read timeout duration for the instance to be built.
* *
* @param duration Read timeout duration. * @param duration Read timeout duration.
* @return Same builder instance. * @return Same builder instance.
*/ */
public DaprHttpBuilder withReadTimeout(Duration duration) { public DaprHttpBuilder withReadTimeout(Duration duration) {
this.readTimeout = duration; this.readTimeout = duration;
return this; return this;
} }
/** /**
* Build an instance of the Http client based on the provided setup. * Build an instance of the Http client based on the provided setup.
* *
* @return an instance of {@link DaprHttp} * @return an instance of {@link DaprHttp}
* @throws IllegalStateException if any required field is missing * @throws IllegalStateException if any required field is missing
*/ */
public DaprHttp build() { public DaprHttp build() {
return buildDaprHttp(); return buildDaprHttp();
} }
/** /**
* Creates and instance of the HTTP Client. * Creates and instance of the HTTP Client.
* *
* @return Instance of {@link DaprHttp} * @return Instance of {@link DaprHttp}
*/ */
private DaprHttp buildDaprHttp() { private DaprHttp buildDaprHttp() {
OkHttpClient.Builder builder = new OkHttpClient.Builder(); OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(DEFAULT_READ_TIMEOUT); builder.readTimeout(DEFAULT_READ_TIMEOUT);
OkHttpClient okHttpClient = builder.build(); OkHttpClient okHttpClient = builder.build();
return new DaprHttp(Properties.HTTP_PORT.get(), okHttpClient); return new DaprHttp(Properties.HTTP_PORT.get(), okHttpClient);
} }
} }

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.client; package io.dapr.client;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
@ -17,114 +18,137 @@ import java.util.Base64;
*/ */
public class ObjectSerializer { public class ObjectSerializer {
/** /**
* Shared Json serializer/deserializer as per Jackson's documentation. * Shared Json serializer/deserializer as per Jackson's documentation.
*/ */
protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper() protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setSerializationInclusion(JsonInclude.Include.NON_NULL); .setSerializationInclusion(JsonInclude.Include.NON_NULL);
/** /**
* Default constructor to avoid class from being instantiated outside package but still inherited. * Default constructor to avoid class from being instantiated outside package but still inherited.
*/ */
protected ObjectSerializer() { protected ObjectSerializer() {
}
/**
* 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 In case state cannot be serialized.
*/
public byte[] serialize(Object state) throws IOException {
if (state == null) {
return null;
} }
/** if (state.getClass() == Void.class) {
* Serializes a given state object into byte array. return null;
*
* @param state State object to be serialized.
* @return Array of bytes[] with the serialized content.
* @throws IOException In case state cannot be serialized.
*/
public byte[] serialize(Object state) throws IOException {
if (state == null) {
return null;
}
if (state.getClass() == Void.class) {
return null;
}
// Have this check here to be consistent with deserialization (see deserialize() method below).
if (state instanceof byte[]) {
return (byte[])state;
}
// This avoids string to be quoted in the state store.
if (state instanceof String) {
return ((String) state).getBytes();
}
// Not string, not primitive, so it is a complex type: we use JSON for that.
return OBJECT_MAPPER.writeValueAsBytes(state);
} }
/** // Have this check here to be consistent with deserialization (see deserialize() method below).
* Deserializes the byte array into the original object. if (state instanceof byte[]) {
* return (byte[]) state;
* @param content Content to be parsed.
* @param clazz Type of the object being deserialized.
* @param <T> Generic type of the object being deserialized.
* @return Object of type T.
* @throws IOException In case content cannot be deserialized.
*/
public <T> T deserialize(byte[] content, Class<T> clazz) throws IOException {
if ((clazz == null) || (clazz == Void.class)) {
return null;
}
if (clazz.isPrimitive()) {
return deserializePrimitives(content, clazz);
}
if (content == null) {
return (T) null;
}
if (clazz == String.class) {
return (T) new String(content);
}
// Deserialization of GRPC response fails without this check since it does not come as base64 encoded byte[].
if (clazz == byte[].class) {
return (T) content;
}
if (content.length == 0) {
return (T) null;
}
if (clazz == CloudEvent.class) {
return (T) CloudEvent.deserialize(content);
}
return OBJECT_MAPPER.readValue(content, clazz);
} }
/** // This avoids string to be quoted in the state store.
* Parses a given String to the corresponding object defined by class. if (state instanceof String) {
* return ((String) state).getBytes();
* @param content Value to be parsed.
* @param clazz Class of the expected result type.
* @param <T> Result type.
* @return Result as corresponding type.
* @throws Exception if cannot deserialize primitive time.
*/
private static <T> T deserializePrimitives(byte[] content, Class<T> clazz) throws IOException {
if ((content == null) || (content.length == 0)) {
if (boolean.class == clazz) return (T) Boolean.FALSE;
if (byte.class == clazz) return (T) Byte.valueOf((byte) 0);
if (short.class == clazz) return (T) Short.valueOf((short) 0);
if (int.class == clazz) return (T) Integer.valueOf(0);
if (long.class == clazz) return (T) Long.valueOf(0L);
if (float.class == clazz) return (T) Float.valueOf(0);
if (double.class == clazz) return (T) Double.valueOf(0);
if (char.class == clazz) return (T) Character.valueOf(Character.MIN_VALUE);
return null;
}
return OBJECT_MAPPER.readValue(content, clazz);
} }
// Not string, not primitive, so it is a complex type: we use JSON for that.
return OBJECT_MAPPER.writeValueAsBytes(state);
}
/**
* Deserializes the byte array into the original object.
*
* @param content Content to be parsed.
* @param clazz Type of the object being deserialized.
* @param <T> Generic type of the object being deserialized.
* @return Object of type T.
* @throws IOException In case content cannot be deserialized.
*/
public <T> T deserialize(byte[] content, Class<T> clazz) throws IOException {
if ((clazz == null) || (clazz == Void.class)) {
return null;
}
if (clazz.isPrimitive()) {
return deserializePrimitives(content, clazz);
}
if (content == null) {
return (T) null;
}
if (clazz == String.class) {
return (T) new String(content);
}
// Deserialization of GRPC response fails without this check since it does not come as base64 encoded byte[].
if (clazz == byte[].class) {
return (T) content;
}
if (content.length == 0) {
return (T) null;
}
if (clazz == CloudEvent.class) {
return (T) CloudEvent.deserialize(content);
}
return OBJECT_MAPPER.readValue(content, clazz);
}
/**
* Parses a given String to the corresponding object defined by class.
*
* @param content Value to be parsed.
* @param clazz Class of the expected result type.
* @param <T> Result type.
* @return Result as corresponding type.
* @throws Exception if cannot deserialize primitive time.
*/
private static <T> T deserializePrimitives(byte[] content, Class<T> clazz) throws IOException {
if ((content == null) || (content.length == 0)) {
if (boolean.class == clazz) {
return (T) Boolean.FALSE;
}
if (byte.class == clazz) {
return (T) Byte.valueOf((byte) 0);
}
if (short.class == clazz) {
return (T) Short.valueOf((short) 0);
}
if (int.class == clazz) {
return (T) Integer.valueOf(0);
}
if (long.class == clazz) {
return (T) Long.valueOf(0L);
}
if (float.class == clazz) {
return (T) Float.valueOf(0);
}
if (double.class == clazz) {
return (T) Double.valueOf(0);
}
if (char.class == clazz) {
return (T) Character.valueOf(Character.MIN_VALUE);
}
return null;
}
return OBJECT_MAPPER.readValue(content, clazz);
}
} }

View File

@ -22,8 +22,8 @@ public final class CloudEvent {
* Shared Json serializer/deserializer as per Jackson's documentation. * Shared Json serializer/deserializer as per Jackson's documentation.
*/ */
protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper() protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setSerializationInclusion(JsonInclude.Include.NON_NULL); .setSerializationInclusion(JsonInclude.Include.NON_NULL);
/** /**
* Identifier of the message being processed. * Identifier of the message being processed.
@ -57,20 +57,21 @@ public final class CloudEvent {
/** /**
* Instantiates a new input request. * Instantiates a new input request.
* @param id Identifier of the message being processed. *
* @param source Source for this event. * @param id Identifier of the message being processed.
* @param type Type of event. * @param source Source for this event.
* @param specversion Version of the event spec. * @param type Type of event.
* @param specversion Version of the event spec.
* @param datacontenttype Type of the payload. * @param datacontenttype Type of the payload.
* @param data Payload. * @param data Payload.
*/ */
public CloudEvent( public CloudEvent(
String id, String id,
String source, String source,
String type, String type,
String specversion, String specversion,
String datacontenttype, String datacontenttype,
String data) { String data) {
this.id = id; this.id = id;
this.source = source; this.source = source;
this.type = type; this.type = type;
@ -81,6 +82,7 @@ public final class CloudEvent {
/** /**
* Gets the identifier of the message being processed. * Gets the identifier of the message being processed.
*
* @return Identifier of the message being processed. * @return Identifier of the message being processed.
*/ */
public String getId() { public String getId() {
@ -89,6 +91,7 @@ public final class CloudEvent {
/** /**
* Gets the source for this event. * Gets the source for this event.
*
* @return Source for this event. * @return Source for this event.
*/ */
public String getSource() { public String getSource() {
@ -97,6 +100,7 @@ public final class CloudEvent {
/** /**
* Gets the type of event. * Gets the type of event.
*
* @return Type of event. * @return Type of event.
*/ */
public String getType() { public String getType() {
@ -105,6 +109,7 @@ public final class CloudEvent {
/** /**
* Gets the version of the event spec. * Gets the version of the event spec.
*
* @return Version of the event spec. * @return Version of the event spec.
*/ */
public String getSpecversion() { public String getSpecversion() {
@ -113,6 +118,7 @@ public final class CloudEvent {
/** /**
* Gets the type of the payload. * Gets the type of the payload.
*
* @return Type of the payload. * @return Type of the payload.
*/ */
public String getDatacontenttype() { public String getDatacontenttype() {
@ -120,7 +126,8 @@ public final class CloudEvent {
} }
/** /**
* Gets the payload * Gets the payload.
*
* @return Payload * @return Payload
*/ */
public String getData() { public String getData() {
@ -129,15 +136,21 @@ public final class CloudEvent {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CloudEvent that = (CloudEvent) o; CloudEvent that = (CloudEvent) o;
return Objects.equals(id, that.id) && return Objects.equals(id, that.id)
Objects.equals(source, that.source) && && Objects.equals(source, that.source)
Objects.equals(type, that.type) && && Objects.equals(type, that.type)
Objects.equals(specversion, that.specversion) && && Objects.equals(specversion, that.specversion)
Objects.equals(datacontenttype, that.datacontenttype) && && Objects.equals(datacontenttype, that.datacontenttype)
Objects.equals(data, that.data); && Objects.equals(data, that.data);
} }
@Override @Override
@ -147,6 +160,7 @@ public final class CloudEvent {
/** /**
* Deserialized a message topic from Dapr. * Deserialized a message topic from Dapr.
*
* @param payload Payload sent from Dapr. * @param payload Payload sent from Dapr.
* @return Message (can be null if input is null) * @return Message (can be null if input is null)
* @throws IOException If cannot parse. * @throws IOException If cannot parse.
@ -158,7 +172,7 @@ public final class CloudEvent {
JsonNode node = OBJECT_MAPPER.readTree(payload); JsonNode node = OBJECT_MAPPER.readTree(payload);
if (node== null) { if (node == null) {
return null; return null;
} }

View File

@ -2,19 +2,21 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.client.domain; package io.dapr.client.domain;
/** /**
* This class reprent what a State is * This class reprent what a State is.
*
* @param <T> The type of the value of the sate * @param <T> The type of the value of the sate
*/ */
public class State<T> { public class State<T> {
/** /**
* The value of the state * The value of the state.
*/ */
private final T value; private final T value;
/** /**
* The key of the state * The key of the state.
*/ */
private final String key; private final String key;
/** /**
@ -24,15 +26,17 @@ public class State<T> {
private final String etag; private final String etag;
/** /**
* The options used for saving the state * The options used for saving the state.
*/ */
private final StateOptions options; private final StateOptions options;
/** /**
* Create an inmutable state * Create an inmutable state
* This Constructor MUST be used anytime you need to retrieve or delete a State. * This Constructor MUST be used anytime you need to retrieve or delete a State.
*
* @param key - The key of the state * @param key - The key of the state
* @param etag - The etag of the state - Keep in mind that for some state stores (like reids) only numbers are supported. * @param etag - The etag of the state - Keep in mind that for some state stores (like redis) only numbers
* are supported.
* @param options - REQUIRED when saving a state. * @param options - REQUIRED when saving a state.
*/ */
public State(String key, String etag, StateOptions options) { public State(String key, String etag, StateOptions options) {
@ -43,11 +47,13 @@ public class State<T> {
} }
/** /**
* Create an inmutable state * Create an inmutable state.
* This Constructor MUST be used anytime you want the state to be send for a Save operation. * This Constructor MUST be used anytime you want the state to be send for a Save operation.
* @param value - The value of the state *
* @param key - The key of the state * @param value - The value of the state.
* @param etag - The etag of the state - Keep in mind that for some state stores (like reids) only numbers are supported. * @param key - The key of the state.
* @param etag - The etag of the state - Keep in mind that for some state stores (like redis)
* only numbers are supported.
* @param options - REQUIRED when saving a state. * @param options - REQUIRED when saving a state.
*/ */
public State(T value, String key, String etag, StateOptions options) { public State(T value, String key, String etag, StateOptions options) {
@ -58,7 +64,8 @@ public class State<T> {
} }
/** /**
* Retrieves the Value of the state * Retrieves the Value of the state.
*
* @return The value of the state * @return The value of the state
*/ */
public T getValue() { public T getValue() {
@ -66,7 +73,8 @@ public class State<T> {
} }
/** /**
* Retrieves the Key of the state * Retrieves the Key of the state.
*
* @return The key of the state * @return The key of the state
*/ */
public String getKey() { public String getKey() {
@ -74,7 +82,8 @@ public class State<T> {
} }
/** /**
* Retrieve the ETag of this state * Retrieve the ETag of this state.
*
* @return The etag of the state * @return The etag of the state
*/ */
public String getEtag() { public String getEtag() {
@ -82,7 +91,8 @@ public class State<T> {
} }
/** /**
* Retrieve the Options used for saving the state * Retrieve the Options used for saving the state.
*
* @return The options to save the state * @return The options to save the state
*/ */
public StateOptions getOptions() { public StateOptions getOptions() {
@ -91,15 +101,31 @@ public class State<T> {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) {
if (!(o instanceof State)) return false; return true;
}
if (!(o instanceof State)) {
return false;
}
State<?> that = (State<?>) o; State<?> that = (State<?>) o;
if (getValue() != null ? !getValue().equals(that.getValue()) : that.getValue() != null) return false; if (getValue() != null ? !getValue().equals(that.getValue()) : that.getValue() != null) {
if (getKey() != null ? !getKey().equals(that.getKey()) : that.getKey() != null) return false; return false;
if (getEtag() != null ? !getEtag().equals(that.getEtag()) : that.getEtag() != null) return false; }
if (getOptions() != null ? !getOptions().equals(that.getOptions()) : that.getOptions() != null) return false;
if (getKey() != null ? !getKey().equals(that.getKey()) : that.getKey() != null) {
return false;
}
if (getEtag() != null ? !getEtag().equals(that.getEtag()) : that.getEtag() != null) {
return false;
}
if (getOptions() != null ? !getOptions().equals(that.getOptions()) : that.getOptions() != null) {
return false;
}
return true; return true;
} }
@ -115,11 +141,11 @@ public class State<T> {
@Override @Override
public String toString() { public String toString() {
return "StateKeyValue{" + return "StateKeyValue{"
"value=" + value + + "value=" + value
", key='" + key + "'" + + ", key='" + key + "'"
", etag='" + etag + "'" + + ", etag='" + etag + "'"
", options={'" + options.toString() + "}" + + ", options={'" + options.toString() + "}"
"}"; + "}";
} }
} }

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.client.domain; package io.dapr.client.domain;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
@ -20,7 +21,6 @@ import io.dapr.utils.DurationUtils;
import java.io.IOException; import java.io.IOException;
import java.time.Duration; import java.time.Duration;
import java.time.temporal.TemporalUnit;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -31,6 +31,12 @@ public class StateOptions {
private final Concurrency concurrency; private final Concurrency concurrency;
private final RetryPolicy retryPolicy; private final RetryPolicy retryPolicy;
/**
* Represents options for a Dapr state API call.
* @param consistency The consistency mode.
* @param concurrency The concurrency mode.
* @param retryPolicy The retry policy.
*/
public StateOptions(Consistency consistency, Concurrency concurrency, RetryPolicy retryPolicy) { public StateOptions(Consistency consistency, Concurrency concurrency, RetryPolicy retryPolicy) {
this.consistency = consistency; this.consistency = consistency;
this.concurrency = concurrency; this.concurrency = concurrency;
@ -49,6 +55,10 @@ public class StateOptions {
return retryPolicy; return retryPolicy;
} }
/**
* Returns state options as a Map of option name to value.
* @return A map of state options.
*/
@JsonIgnore @JsonIgnore
public Map<String, String> getStateOptionsAsMap() { public Map<String, String> getStateOptionsAsMap() {
Map<String, String> mapOptions = null; Map<String, String> mapOptions = null;
@ -98,7 +108,7 @@ public class StateOptions {
public enum Concurrency { public enum Concurrency {
FIRST_WRITE("first-write"), FIRST_WRITE("first-write"),
LAST_WRITE ("last-write"); LAST_WRITE("last-write");
private final String value; private final String value;
@ -146,6 +156,12 @@ public class StateOptions {
private final Pattern pattern; private final Pattern pattern;
/**
* Represents retry policies on a state operation.
* @param interval The delay between retries.
* @param threshold The total number of retries.
* @param pattern The way to retry: linear or exponential.
*/
public RetryPolicy(Duration interval, Integer threshold, Pattern pattern) { public RetryPolicy(Duration interval, Integer threshold, Pattern pattern) {
this.interval = interval; this.interval = interval;
this.threshold = threshold; this.threshold = threshold;
@ -171,12 +187,16 @@ public class StateOptions {
super(Duration.class); super(Duration.class);
} }
public StateOptionDurationSerializer(Class<Duration> t) { public StateOptionDurationSerializer(Class<Duration> t) {
super(t); super(t);
} }
@Override @Override
public void serialize(Duration duration, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { public void serialize(
Duration duration,
JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeNumber(duration.toMillis()); jsonGenerator.writeNumber(duration.toMillis());
} }
} }
@ -187,12 +207,14 @@ public class StateOptions {
} }
@Override @Override
public Duration deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { public Duration deserialize(
JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException {
String durationStr = jsonParser.readValueAs(String.class); String durationStr = jsonParser.readValueAs(String.class);
Duration duration = null; Duration duration = null;
if (durationStr != null && !durationStr.trim().isEmpty()) { if (durationStr != null && !durationStr.trim().isEmpty()) {
try { try {
duration = DurationUtils.ConvertDurationFromDaprFormat(durationStr); duration = DurationUtils.convertDurationFromDaprFormat(durationStr);
} catch (Exception ex) { } catch (Exception ex) {
throw InvalidFormatException.from(jsonParser, "Unable to parse duration.", ex); throw InvalidFormatException.from(jsonParser, "Unable to parse duration.", ex);
} }

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.client.domain; package io.dapr.client.domain;
/** /**

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.exceptions; package io.dapr.exceptions;
/** /**
@ -9,54 +10,54 @@ package io.dapr.exceptions;
*/ */
public class DaprError { public class DaprError {
/** /**
* Error code. * Error code.
*/ */
private String errorCode; private String errorCode;
/** /**
* Error Message. * Error Message.
*/ */
private String message; private String message;
/** /**
* Gets the error code. * Gets the error code.
* *
* @return Error code. * @return Error code.
*/ */
public String getErrorCode() { public String getErrorCode() {
return errorCode; return errorCode;
} }
/** /**
* Sets the error code. * Sets the error code.
* *
* @param errorCode Error code. * @param errorCode Error code.
* @return This instance. * @return This instance.
*/ */
public DaprError setErrorCode(String errorCode) { public DaprError setErrorCode(String errorCode) {
this.errorCode = errorCode; this.errorCode = errorCode;
return this; return this;
} }
/** /**
* Gets the error message. * Gets the error message.
* *
* @return Error message. * @return Error message.
*/ */
public String getMessage() { public String getMessage() {
return message; return message;
} }
/** /**
* Sets the error message. * Sets the error message.
* *
* @param message Error message. * @param message Error message.
* @return This instance. * @return This instance.
*/ */
public DaprError setMessage(String message) { public DaprError setMessage(String message) {
this.message = message; this.message = message;
return this; return this;
} }
} }

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.exceptions; package io.dapr.exceptions;
/** /**
@ -9,63 +10,63 @@ package io.dapr.exceptions;
*/ */
public class DaprException extends RuntimeException { public class DaprException extends RuntimeException {
/** /**
* Dapr's error code for this exception. * Dapr's error code for this exception.
*/ */
private String errorCode; private String errorCode;
/** /**
* New exception from a server-side generated error code and message. * New exception from a server-side generated error code and message.
* *
* @param daprError Server-side error. * @param daprError Server-side error.
*/ */
public DaprException(DaprError daprError) { public DaprException(DaprError daprError) {
this(daprError.getErrorCode(), daprError.getMessage()); this(daprError.getErrorCode(), daprError.getMessage());
} }
/** /**
* * New exception from a server-side generated error code and message.
* @param daprError Client-side error. * @param daprError Client-side error.
* @param cause the cause (which is saved for later retrieval by the * @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is * {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or * permitted, and indicates that the cause is nonexistent or
* unknown.) * unknown.)
*/ */
public DaprException(DaprError daprError, Throwable cause) { public DaprException(DaprError daprError, Throwable cause) {
this(daprError.getErrorCode(), daprError.getMessage(), cause); this(daprError.getErrorCode(), daprError.getMessage(), cause);
} }
/** /**
* New Exception from a client-side generated error code and message. * New Exception from a client-side generated error code and message.
* *
* @param errorCode Client-side error code. * @param errorCode Client-side error code.
* @param message Client-side error message. * @param message Client-side error message.
*/ */
public DaprException(String errorCode, String message) { public DaprException(String errorCode, String message) {
super(String.format("%s: %s", errorCode, message)); super(String.format("%s: %s", errorCode, message));
this.errorCode = errorCode; this.errorCode = errorCode;
} }
/** /**
* * New exception from a server-side generated error code and message.
* @param errorCode Client-side error code. * @param errorCode Client-side error code.
* @param message Client-side error message. * @param message Client-side error message.
* @param cause the cause (which is saved for later retrieval by the * @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is * {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or * permitted, and indicates that the cause is nonexistent or
* unknown.) * unknown.)
*/ */
public DaprException(String errorCode, String message, Throwable cause) { public DaprException(String errorCode, String message, Throwable cause) {
super(String.format("%s: %s", errorCode, message), cause); super(String.format("%s: %s", errorCode, message), cause);
this.errorCode = errorCode; this.errorCode = errorCode;
} }
/** /**
* Returns the exception's error code. * Returns the exception's error code.
* *
* @return Error code. * @return Error code.
*/ */
public String getErrorCode() { public String getErrorCode() {
return this.errorCode; return this.errorCode;
} }
} }

View File

@ -5,13 +5,17 @@
package io.dapr.serializer; package io.dapr.serializer;
import java.lang.annotation.*; import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** /**
* Flags a serializer indicating that byte[] contains String for both input and output. * Flags a serializer indicating that byte[] contains String for both input and output.
*
* This information can be used to at the state store, for example, to save serialized data as plain text. * This information can be used to at the state store, for example, to save serialized data as plain text.
*/ */
@Documented @Documented
@Target({ElementType.TYPE_USE}) @Target({ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation. * Copyright (c) Microsoft Corporation.
* Licensed under the MIT License. * Licensed under the MIT License.
*/ */
package io.dapr.utils; package io.dapr.utils;
/** /**
@ -9,73 +10,73 @@ package io.dapr.utils;
*/ */
public final class Constants { public final class Constants {
/** /**
* Dapr API used in this client. * Dapr API used in this client.
*/ */
public static final String API_VERSION = "v1.0"; public static final String API_VERSION = "v1.0";
/** /**
* Dapr's default hostname. * Dapr's default hostname.
*/ */
public static final String DEFAULT_HOSTNAME = "localhost"; public static final String DEFAULT_HOSTNAME = "localhost";
/** /**
* Header used for request id in Dapr. * Header used for request id in Dapr.
*/ */
public static final String HEADER_DAPR_REQUEST_ID = "X-DaprRequestId"; public static final String HEADER_DAPR_REQUEST_ID = "X-DaprRequestId";
/** /**
* Header for the conditional operation. * Header for the conditional operation.
*/ */
public static final String HEADER_HTTP_ETAG_ID = "If-Match"; public static final String HEADER_HTTP_ETAG_ID = "If-Match";
/** /**
* Base URL for Dapr Actor APIs. * Base URL for Dapr Actor APIs.
*/ */
private static final String ACTORS_BASE_URL = API_VERSION + "/" + "actors"; private static final String ACTORS_BASE_URL = API_VERSION + "/" + "actors";
/** /**
* String format for Actors state management relative url. * String format for Actors state management relative url.
*/ */
public static final String ACTOR_STATE_KEY_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/state/%s"; public static final String ACTOR_STATE_KEY_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/state/%s";
/** /**
* String format for Actors state management relative url. * String format for Actors state management relative url.
*/ */
public static final String ACTOR_STATE_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/state"; public static final String ACTOR_STATE_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/state";
/** /**
* String format for Actors method invocation relative url. * String format for Actors method invocation relative url.
*/ */
public static final String ACTOR_METHOD_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/method/%s"; public static final String ACTOR_METHOD_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/method/%s";
/** /**
* String format for Actors reminder registration relative url.. * String format for Actors reminder registration relative url..
*/ */
public static final String ACTOR_REMINDER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/reminders/%s"; public static final String ACTOR_REMINDER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/reminders/%s";
/** /**
* String format for Actors timer registration relative url.. * String format for Actors timer registration relative url..
*/ */
public static final String ACTOR_TIMER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/timers/%s"; public static final String ACTOR_TIMER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/timers/%s";
/** /**
* Base path to invoke methods. * Base path to invoke methods.
*/ */
public static final String INVOKE_PATH = API_VERSION + "/invoke"; public static final String INVOKE_PATH = API_VERSION + "/invoke";
/** /**
* Invoke Publish Path * Invoke Publish Path.
*/ */
public static final String PUBLISH_PATH = API_VERSION + "/publish"; public static final String PUBLISH_PATH = API_VERSION + "/publish";
/** /**
* Invoke Binding Path * Invoke Binding Path.
*/ */
public static final String BINDING_PATH = API_VERSION + "/bindings"; public static final String BINDING_PATH = API_VERSION + "/bindings";
/** /**
* State Path * State Path.
*/ */
public static final String STATE_PATH = API_VERSION + "/state"; public static final String STATE_PATH = API_VERSION + "/state";
} }

View File

@ -15,27 +15,27 @@ public class DurationUtils {
* @param valueString A String representing time in the Dapr runtime's format (e.g. 4h15m50s60ms). * @param valueString A String representing time in the Dapr runtime's format (e.g. 4h15m50s60ms).
* @return A Duration * @return A Duration
*/ */
public static Duration ConvertDurationFromDaprFormat(String valueString) { public static Duration convertDurationFromDaprFormat(String valueString) {
// Convert the format returned by the Dapr runtime into Duration // Convert the format returned by the Dapr runtime into Duration
// An example of the format is: 4h15m50s60ms. It does not include days. // An example of the format is: 4h15m50s60ms. It does not include days.
int hIndex = valueString.indexOf('h'); int hourIndex = valueString.indexOf('h');
int mIndex = valueString.indexOf('m'); int minuteIndex = valueString.indexOf('m');
int sIndex = valueString.indexOf('s'); int secondIndex = valueString.indexOf('s');
int msIndex = valueString.indexOf("ms"); int milliIndex = valueString.indexOf("ms");
String hoursSpan = valueString.substring(0, hIndex); String hoursSpan = valueString.substring(0, hourIndex);
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(hourIndex + 1, minuteIndex);
int minutes = Integer.parseInt(minutesSpan); int minutes = Integer.parseInt(minutesSpan);
String secondsSpan = valueString.substring(mIndex + 1, sIndex); String secondsSpan = valueString.substring(minuteIndex + 1, secondIndex);
int seconds = Integer.parseInt(secondsSpan); int seconds = Integer.parseInt(secondsSpan);
String millisecondsSpan = valueString.substring(sIndex + 1, msIndex); String millisecondsSpan = valueString.substring(secondIndex + 1, milliIndex);
int milliseconds = Integer.parseInt(millisecondsSpan); int milliseconds = Integer.parseInt(millisecondsSpan);
return Duration.ZERO return Duration.ZERO
@ -52,13 +52,13 @@ public class DurationUtils {
* @param value Duration * @param value Duration
* @return The Duration formatted as a String in the format the Dapr runtime uses (e.g. 4h15m50s60ms) * @return The Duration formatted as a String in the format the Dapr runtime uses (e.g. 4h15m50s60ms)
*/ */
public static String ConvertDurationToDaprFormat(Duration value) { public static String convertDurationToDaprFormat(Duration value) {
String stringValue = ""; String stringValue = "";
// return empty string for anything negative, it'll only happen for reminder "periods", not dueTimes. A // return empty string for anything negative, it'll only happen for reminder "periods", not dueTimes. A
// negative "period" means fire once only. // negative "period" means fire once only.
if (value == Duration.ZERO || if (value == Duration.ZERO
(value.compareTo(Duration.ZERO) == 1)) { || (value.compareTo(Duration.ZERO) == 1)) {
long hours = getDaysPart(value) * 24 + getHoursPart(value); long hours = getDaysPart(value) * 24 + getHoursPart(value);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -93,7 +93,8 @@ public class DurationUtils {
} }
/** /**
* 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. * 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 d The duration to parse * @param d The duration to parse
* @return the hour part of the duration * @return the hour part of the duration

View File

@ -32,19 +32,22 @@ public class Properties {
* HTTP port for Dapr after checking system property and environment variable. * HTTP port for Dapr after checking system property and environment variable.
*/ */
public static final Supplier<Integer> HTTP_PORT = () -> getIntOrDefault( public static final Supplier<Integer> HTTP_PORT = () -> getIntOrDefault(
"dapr.http.port", "DAPR_HTTP_PORT", DEFAULT_HTTP_PORT); "dapr.http.port",
"DAPR_HTTP_PORT", DEFAULT_HTTP_PORT);
/** /**
* GRPC port for Dapr after checking system property and environment variable. * GRPC port for Dapr after checking system property and environment variable.
*/ */
public static final Supplier<Integer> GRPC_PORT = () -> getIntOrDefault( public static final Supplier<Integer> GRPC_PORT = () -> getIntOrDefault(
"dapr.grpc.port", "DAPR_GRPC_PORT", DEFAULT_GRPC_PORT); "dapr.grpc.port",
"DAPR_GRPC_PORT", DEFAULT_GRPC_PORT);
/** /**
* Determines if Dapr client will use GRPC to talk to Dapr's side car. * Determines if Dapr client will use GRPC to talk to Dapr's side car.
*/ */
public static final Supplier<Boolean> USE_GRPC = () -> getBooleanOrDefault( public static final Supplier<Boolean> USE_GRPC = () -> getBooleanOrDefault(
"dapr.grpc.enabled", "DAPR_GRPC_ENABLED", DEFAULT_GRPC_ENABLED); "dapr.grpc.enabled",
"DAPR_GRPC_ENABLED", DEFAULT_GRPC_ENABLED);
/** /**
* Finds an integer defined by system property first, then env variable or sticks to default. * Finds an integer defined by system property first, then env variable or sticks to default.

View File

@ -32,7 +32,7 @@ public class DaprHttpStub extends DaprHttp {
* @return * @return
*/ */
@Override @Override
public Mono<DaprHttp.Response> invokeAPI(String method, String urlString, Map<String, String> urlParameters, Map<String, String> headers) { public Mono<DaprHttp.Response> invokeApi(String method, String urlString, Map<String, String> urlParameters, Map<String, String> headers) {
return Mono.empty(); return Mono.empty();
} }
@ -40,7 +40,7 @@ public class DaprHttpStub extends DaprHttp {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Mono<DaprHttp.Response> invokeAPI(String method, String urlString, Map<String, String> urlParameters, String content, Map<String, String> headers) { public Mono<DaprHttp.Response> invokeApi(String method, String urlString, Map<String, String> urlParameters, String content, Map<String, String> headers) {
return Mono.empty(); return Mono.empty();
} }
@ -48,7 +48,7 @@ public class DaprHttpStub extends DaprHttp {
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override @Override
public Mono<DaprHttp.Response> invokeAPI(String method, String urlString, Map<String, String> urlParameters, byte[] content, Map<String, String> headers) { public Mono<DaprHttp.Response> invokeApi(String method, String urlString, Map<String, String> urlParameters, byte[] content, Map<String, String> headers) {
return Mono.empty(); return Mono.empty();
} }
} }

View File

@ -45,7 +45,7 @@ public class DaprHttpTest {
.post("http://localhost:3500/v1.0/state") .post("http://localhost:3500/v1.0/state")
.respond(serializer.serialize(EXPECTED_RESULT)); .respond(serializer.serialize(EXPECTED_RESULT));
DaprHttp daprHttp = new DaprHttp(3500, okHttpClient); DaprHttp daprHttp = new DaprHttp(3500, okHttpClient);
Mono<DaprHttp.Response> mono = daprHttp.invokeAPI("POST", "v1.0/state", null, (byte[]) null, headers); Mono<DaprHttp.Response> mono = daprHttp.invokeApi("POST", "v1.0/state", null, (byte[]) null, headers);
DaprHttp.Response response = mono.block(); DaprHttp.Response response = mono.block();
String body = serializer.deserialize(response.getBody(), String.class); String body = serializer.deserialize(response.getBody(), String.class);
assertEquals(EXPECTED_RESULT, body); assertEquals(EXPECTED_RESULT, body);
@ -58,7 +58,7 @@ public class DaprHttpTest {
.respond(serializer.serialize(EXPECTED_RESULT)) .respond(serializer.serialize(EXPECTED_RESULT))
.addHeader("Header", "Value"); .addHeader("Header", "Value");
DaprHttp daprHttp = new DaprHttp(3500, okHttpClient); DaprHttp daprHttp = new DaprHttp(3500, okHttpClient);
Mono<DaprHttp.Response> mono = daprHttp.invokeAPI("POST", "v1.0/state", null, "", null); Mono<DaprHttp.Response> mono = daprHttp.invokeApi("POST", "v1.0/state", null, "", null);
DaprHttp.Response response = mono.block(); DaprHttp.Response response = mono.block();
String body = serializer.deserialize(response.getBody(), String.class); String body = serializer.deserialize(response.getBody(), String.class);
assertEquals(EXPECTED_RESULT, body); assertEquals(EXPECTED_RESULT, body);
@ -70,7 +70,7 @@ public class DaprHttpTest {
.delete("http://localhost:3500/v1.0/state") .delete("http://localhost:3500/v1.0/state")
.respond(serializer.serialize(EXPECTED_RESULT)); .respond(serializer.serialize(EXPECTED_RESULT));
DaprHttp daprHttp = new DaprHttp(3500, okHttpClient); DaprHttp daprHttp = new DaprHttp(3500, okHttpClient);
Mono<DaprHttp.Response> mono = daprHttp.invokeAPI("DELETE", "v1.0/state", null, (String) null, null); Mono<DaprHttp.Response> mono = daprHttp.invokeApi("DELETE", "v1.0/state", null, (String) null, null);
DaprHttp.Response response = mono.block(); DaprHttp.Response response = mono.block();
String body = serializer.deserialize(response.getBody(), String.class); String body = serializer.deserialize(response.getBody(), String.class);
assertEquals(EXPECTED_RESULT, body); assertEquals(EXPECTED_RESULT, body);
@ -82,7 +82,7 @@ public class DaprHttpTest {
.get("http://localhost:3500/v1.0/get") .get("http://localhost:3500/v1.0/get")
.respond(serializer.serialize(EXPECTED_RESULT)); .respond(serializer.serialize(EXPECTED_RESULT));
DaprHttp daprHttp = new DaprHttp(3500, okHttpClient); DaprHttp daprHttp = new DaprHttp(3500, okHttpClient);
Mono<DaprHttp.Response> mono = daprHttp.invokeAPI("GET", "v1.0/get", null, null); Mono<DaprHttp.Response> mono = daprHttp.invokeApi("GET", "v1.0/get", null, null);
DaprHttp.Response response = mono.block(); DaprHttp.Response response = mono.block();
String body = serializer.deserialize(response.getBody(), String.class); String body = serializer.deserialize(response.getBody(), String.class);
assertEquals(EXPECTED_RESULT, body); assertEquals(EXPECTED_RESULT, body);
@ -99,7 +99,7 @@ public class DaprHttpTest {
.get("http://localhost:3500/v1.0/state/order?orderId=41") .get("http://localhost:3500/v1.0/state/order?orderId=41")
.respond(serializer.serialize(EXPECTED_RESULT)); .respond(serializer.serialize(EXPECTED_RESULT));
DaprHttp daprHttp = new DaprHttp(3500, okHttpClient); DaprHttp daprHttp = new DaprHttp(3500, okHttpClient);
Mono<DaprHttp.Response> mono = daprHttp.invokeAPI("GET", "v1.0/state/order", urlParameters, headers); Mono<DaprHttp.Response> mono = daprHttp.invokeApi("GET", "v1.0/state/order", urlParameters, headers);
DaprHttp.Response response = mono.block(); DaprHttp.Response response = mono.block();
String body = serializer.deserialize(response.getBody(), String.class); String body = serializer.deserialize(response.getBody(), String.class);
assertEquals(EXPECTED_RESULT, body); assertEquals(EXPECTED_RESULT, body);
@ -111,7 +111,7 @@ public class DaprHttpTest {
.post("http://localhost:3500/v1.0/state") .post("http://localhost:3500/v1.0/state")
.respond(500); .respond(500);
DaprHttp daprHttp = new DaprHttp(3500, okHttpClient); DaprHttp daprHttp = new DaprHttp(3500, okHttpClient);
Mono<DaprHttp.Response> mono = daprHttp.invokeAPI("POST", "v1.0/state", null, null); Mono<DaprHttp.Response> mono = daprHttp.invokeApi("POST", "v1.0/state", null, null);
DaprHttp.Response response = mono.block(); DaprHttp.Response response = mono.block();
String body = serializer.deserialize(response.getBody(), String.class); String body = serializer.deserialize(response.getBody(), String.class);
assertEquals(EXPECTED_RESULT, body); assertEquals(EXPECTED_RESULT, body);
@ -124,7 +124,7 @@ public class DaprHttpTest {
.respond(500, ResponseBody.create(MediaType.parse("text"), .respond(500, ResponseBody.create(MediaType.parse("text"),
"{\"errorCode\":null,\"message\":null}")); "{\"errorCode\":null,\"message\":null}"));
DaprHttp daprHttp = new DaprHttp(3500, okHttpClient); DaprHttp daprHttp = new DaprHttp(3500, okHttpClient);
Mono<DaprHttp.Response> mono = daprHttp.invokeAPI("POST", "v1.0/state", null, null); Mono<DaprHttp.Response> mono = daprHttp.invokeApi("POST", "v1.0/state", null, null);
DaprHttp.Response response = mono.block(); DaprHttp.Response response = mono.block();
String body = serializer.deserialize(response.getBody(), String.class); String body = serializer.deserialize(response.getBody(), String.class);
assertEquals(EXPECTED_RESULT, body); assertEquals(EXPECTED_RESULT, body);
@ -137,7 +137,7 @@ public class DaprHttpTest {
.respond(500, ResponseBody.create(MediaType.parse("application/json"), .respond(500, ResponseBody.create(MediaType.parse("application/json"),
"{\"errorCode\":\"null\",\"message\":\"null\"}")); "{\"errorCode\":\"null\",\"message\":\"null\"}"));
DaprHttp daprHttp = new DaprHttp(3500, okHttpClient); DaprHttp daprHttp = new DaprHttp(3500, okHttpClient);
Mono<DaprHttp.Response> mono = daprHttp.invokeAPI("POST", "v1.0/state", null, null); Mono<DaprHttp.Response> mono = daprHttp.invokeApi("POST", "v1.0/state", null, null);
DaprHttp.Response response = mono.block(); DaprHttp.Response response = mono.block();
String body = serializer.deserialize(response.getBody(), String.class); String body = serializer.deserialize(response.getBody(), String.class);
assertEquals(EXPECTED_RESULT, body); assertEquals(EXPECTED_RESULT, body);
@ -180,10 +180,10 @@ public class DaprHttpTest {
.respond(200, ResponseBody.create(MediaType.parse("application/json"), .respond(200, ResponseBody.create(MediaType.parse("application/json"),
serializer.serialize(existingState))); serializer.serialize(existingState)));
DaprHttp daprHttp = new DaprHttp(3500, okHttpClient); DaprHttp daprHttp = new DaprHttp(3500, okHttpClient);
Mono<DaprHttp.Response> response = daprHttp.invokeAPI("GET", urlExistingState, null, null); Mono<DaprHttp.Response> response = daprHttp.invokeApi("GET", urlExistingState, null, null);
assertEquals(existingState, serializer.deserialize(response.block().getBody(), String.class)); assertEquals(existingState, serializer.deserialize(response.block().getBody(), String.class));
Mono<DaprHttp.Response> responseDeleted = daprHttp.invokeAPI("GET", urlDeleteState, null, null); Mono<DaprHttp.Response> responseDeleted = daprHttp.invokeApi("GET", urlDeleteState, null, null);
Mono<DaprHttp.Response> responseDeleteKey = daprHttp.invokeAPI("DELETE", urlDeleteState, null, null); Mono<DaprHttp.Response> responseDeleteKey = daprHttp.invokeApi("DELETE", urlDeleteState, null, null);
assertEquals("", serializer.deserialize(responseDeleteKey.block().getBody(), String.class)); assertEquals("", serializer.deserialize(responseDeleteKey.block().getBody(), String.class));
mockInterceptor.reset(); mockInterceptor.reset();
mockInterceptor.addRule() mockInterceptor.addRule()

View File

@ -110,7 +110,7 @@ public class DaprRuntimeTest {
DaprObjectSerializer serializer = new DefaultObjectSerializer(); DaprObjectSerializer serializer = new DefaultObjectSerializer();
for (Message message : messages) { for (Message message : messages) {
when(daprHttp.invokeAPI( when(daprHttp.invokeApi(
eq("POST"), eq("POST"),
eq(Constants.PUBLISH_PATH + "/" + TOPIC_NAME), eq(Constants.PUBLISH_PATH + "/" + TOPIC_NAME),
eq(null), eq(null),
@ -197,7 +197,7 @@ public class DaprRuntimeTest {
when(listener.process(eq(serializer.serialize(message.data)), eq(message.metadata))) when(listener.process(eq(serializer.serialize(message.data)), eq(message.metadata)))
.then(x -> expectedResponse == null ? Mono.empty() : Mono.just(expectedResponse)); .then(x -> expectedResponse == null ? Mono.empty() : Mono.just(expectedResponse));
when(daprHttp.invokeAPI( when(daprHttp.invokeApi(
eq("POST"), eq("POST"),
eq(Constants.INVOKE_PATH + "/" + APP_ID + "/method/" + METHOD_NAME), eq(Constants.INVOKE_PATH + "/" + APP_ID + "/method/" + METHOD_NAME),
eq(null), eq(null),

View File

@ -10,9 +10,9 @@ public class DurationUtilsTest {
@Test @Test
public void convertTimeBothWays() { public void convertTimeBothWays() {
String s = "4h15m50s60ms"; String s = "4h15m50s60ms";
Duration d1 = DurationUtils.ConvertDurationFromDaprFormat(s); Duration d1 = DurationUtils.convertDurationFromDaprFormat(s);
String t = DurationUtils.ConvertDurationToDaprFormat(d1); String t = DurationUtils.convertDurationToDaprFormat(d1);
Assert.assertEquals(s, t); Assert.assertEquals(s, t);
} }
@ -20,16 +20,16 @@ public class DurationUtilsTest {
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 = DurationUtils.ConvertDurationFromDaprFormat(s); Duration d1 = DurationUtils.convertDurationFromDaprFormat(s);
String t = DurationUtils.ConvertDurationToDaprFormat(d1); String t = DurationUtils.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 = DurationUtils.ConvertDurationToDaprFormat(d); String t = DurationUtils.convertDurationToDaprFormat(d);
Assert.assertEquals("", t); Assert.assertEquals("", t);
} }