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.client.ActorProxy;
import io.dapr.actors.client.ActorProxyBuilder;
import io.dapr.serializer.DefaultObjectSerializer;
import java.util.ArrayList;
import java.util.List;
@ -22,7 +21,8 @@ import java.util.concurrent.TimeUnit;
* 1. Build and install jars:
* mvn clean install
* 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 {
@ -34,6 +34,11 @@ public class DemoActorClient {
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 {
ActorProxyBuilder builder = new ActorProxyBuilder("DemoActor");
@ -57,10 +62,10 @@ public class DemoActorClient {
for (int i = 0; i < NUM_MESSAGES_PER_ACTOR; i++) {
actor.invokeActorMethod("incrementAndGet", 1).block();
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));
try {
Thread.sleep((long)(1000 * Math.random()));
Thread.sleep((long) (1000 * Math.random()));
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
@ -69,7 +74,7 @@ public class DemoActorClient {
}
System.out.println(
"Messages sent: " + actor.invokeActorMethod("incrementAndGet", 0, int.class).block());
"Messages sent: " + actor.invokeActorMethod("incrementAndGet", 0, int.class).block());
}, POOL);
}
}

View File

@ -10,7 +10,6 @@ import io.dapr.actors.runtime.AbstractActor;
import io.dapr.actors.runtime.ActorRuntimeContext;
import io.dapr.actors.runtime.ActorType;
import io.dapr.actors.runtime.Remindable;
import reactor.core.publisher.Mono;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
@ -18,6 +17,8 @@ import java.time.Duration;
import java.util.Calendar;
import java.util.TimeZone;
import reactor.core.publisher.Mono;
/**
* 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");
/**
* 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) {
super(runtimeContext, id);
super.registerActorTimer(
null,
"clock",
"ping!",
Duration.ofSeconds(2),
Duration.ofSeconds(1)).block();
null,
"clock",
"ping!",
Duration.ofSeconds(2),
Duration.ofSeconds(1)).block();
}
@Override
public void registerReminder() {
super.registerReminder(
"myremind",
(int)(Integer.MAX_VALUE * Math.random()),
Duration.ofSeconds(5),
Duration.ofSeconds(2)).block();
"myremind",
(int) (Integer.MAX_VALUE * Math.random()),
Duration.ofSeconds(5),
Duration.ofSeconds(2)).block();
}
@Override
@ -55,9 +61,9 @@ public class DemoActorImpl extends AbstractActor implements DemoActor, Remindabl
String utcNowAsString = DATE_FORMAT.format(utcNow.getTime());
// Handles the request by printing message.
System.out.println("Server say method for actor " +
super.getId() + ": " +
(something == null ? "" : something + " @ " + utcNowAsString));
System.out.println("Server say method for actor "
+ super.getId() + ": "
+ (something == null ? "" : something + " @ " + utcNowAsString));
super.getActorStateManager().set("lastmessage", something).block();
@ -68,9 +74,9 @@ public class DemoActorImpl extends AbstractActor implements DemoActor, Remindabl
@Override
public Mono<Integer> incrementAndGet(int delta) {
return super.getActorStateManager().contains("counter")
.flatMap(exists -> exists ? super.getActorStateManager().get("counter", int.class) : Mono.just(0))
.map(c -> c + delta)
.flatMap(c -> super.getActorStateManager().set("counter", c).thenReturn(c));
.flatMap(exists -> exists ? super.getActorStateManager().get("counter", int.class) : Mono.just(0))
.map(c -> c + delta)
.flatMap(c -> super.getActorStateManager().set("counter", c).thenReturn(c));
}
@Override
@ -79,9 +85,9 @@ public class DemoActorImpl extends AbstractActor implements DemoActor, Remindabl
String utcNowAsString = DATE_FORMAT.format(utcNow.getTime());
// Handles the request by printing message.
System.out.println("Server timer for actor " +
super.getId() + ": " +
(message == null ? "" : message + " @ " + utcNowAsString));
System.out.println("Server timer for actor "
+ super.getId() + ": "
+ (message == null ? "" : message + " @ " + utcNowAsString));
}
@Override
@ -96,8 +102,8 @@ public class DemoActorImpl extends AbstractActor implements DemoActor, Remindabl
// Handles the request by printing message.
System.out.println(String.format(
"Server reminded actor %s of: %s for %d @ %s",
this.getId(), reminderName, state, utcNowAsString));
"Server reminded actor %s of: %s for %d @ %s",
this.getId(), reminderName, state, utcNowAsString));
return Mono.empty();
}
}

View File

@ -20,14 +20,20 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
* 1. Build and install jars:
* mvn clean install
* 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
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 {
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();
CommandLine cmd = parser.parse(options, args);
@ -37,7 +43,7 @@ public class DemoActorService {
// Register the Actor class.
ActorRuntime.getInstance().registerActor(
DemoActorImpl.class, new DefaultObjectSerializer(), new DefaultObjectSerializer());
DemoActorImpl.class, new DefaultObjectSerializer(), new DefaultObjectSerializer());
// Start Dapr's callback endpoint.
DaprApplication.start(port);

View File

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

View File

@ -17,13 +17,19 @@ import org.apache.commons.cli.Options;
* mvn clean install
* 2. cd to [repo-root]/examples
* 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 {
/**
* 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 {
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();
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.DaprClientBuilder;
import io.dapr.serializer.DefaultObjectSerializer;
/**
* Service for output binding example.
* 1. From your repo root, build and install jars:
* mvn clean install
* mvn clean install
* 2. cd to [repo-root]/examples
* 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 static class MyClass {
public MyClass(){}
public MyClass() {
}
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) {
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:
// {"message":"hello"}
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;
import static io.dapr.examples.DaprExamplesProtos.SayRequest;
import static io.dapr.examples.DaprExamplesProtos.SayResponse;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException;
@ -8,24 +16,23 @@ import io.dapr.DaprProtos.InvokeServiceEnvelope;
import io.dapr.DaprProtos.InvokeServiceResponseEnvelope;
import io.grpc.ManagedChannel;
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.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
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:
* mvn clean install
* 2. Send messages to the server:
* dapr run --protocol grpc --grpc-port 50001 -- mvn exec:java -pl=examples -Dexec.mainClass=io.dapr.examples.invoke.grpc.HelloWorldClient -Dexec.args="-p 50001 'message one' 'message two'"
* dapr run --protocol grpc --grpc-port 50001 -- mvn exec:java -pl=examples \
* -Dexec.mainClass=io.dapr.examples.invoke.grpc.HelloWorldClient \
* -Dexec.args="-p 50001 'message one' 'message two'"
*/
public class HelloWorldClient {
@ -35,7 +42,7 @@ public class HelloWorldClient {
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;
@ -52,15 +59,15 @@ public class HelloWorldClient {
*/
public GrpcHelloWorldDaprClient(String host, int port) {
this(ManagedChannelBuilder
.forAddress("localhost", port)
.usePlaintext() // SSL/TLS is default, we turn it off just because this is a sample and not prod.
.build());
.forAddress("localhost", port)
.usePlaintext() // SSL/TLS is default, we turn it off just because this is a sample and not prod.
.build());
}
/**
* Helper constructor to build client from channel.
*
* @param channel
* @param channel The ManagedChannel.
*/
private GrpcHelloWorldDaprClient(ManagedChannel channel) {
this.channel = channel;
@ -70,23 +77,24 @@ public class HelloWorldClient {
/**
* 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<>();
for (String message : messages) {
SayRequest request = SayRequest
.newBuilder()
.setMessage(message)
.build();
.newBuilder()
.setMessage(message)
.build();
// Now, wrap the request with Dapr's envelope.
InvokeServiceEnvelope requestEnvelope = InvokeServiceEnvelope
.newBuilder()
.setId("hellogrpc") // Service's identifier.
.setData(Any.pack(request))
.setMethod("say") // The service's method to be invoked by Dapr.
.build();
.newBuilder()
.setId("hellogrpc") // Service's identifier.
.setData(Any.pack(request))
.setMethod("say") // The service's method to be invoked by Dapr.
.build();
futureResponses.add(client.invokeService(requestEnvelope));
System.out.println("Client: sent => " + message);
@ -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 {
Options options = new Options();
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;
import static io.dapr.examples.DaprExamplesProtos.SayRequest;
import static io.dapr.examples.DaprExamplesProtos.SayResponse;
import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException;
import io.dapr.DaprClientGrpc;
@ -7,25 +15,23 @@ import io.dapr.DaprClientProtos;
import io.grpc.Server;
import io.grpc.ServerBuilder;
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.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import static io.dapr.examples.DaprExamplesProtos.SayRequest;
import static io.dapr.examples.DaprExamplesProtos.SayResponse;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
/**
* 1. Build and install jars:
* mvn clean install
* 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 {
@ -52,10 +58,10 @@ public class HelloWorldService {
*/
private void start(int port) throws IOException {
this.server = ServerBuilder
.forPort(port)
.addService(this)
.build()
.start();
.forPort(port)
.addService(this)
.build()
.start();
System.out.printf("Server: started listening on port %d\n", port);
// Now we handle ctrl+c (or any other JVM shutdown)
@ -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 {
Options options = new Options();
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:
* mvn clean install
* 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 {

View File

@ -6,11 +6,6 @@
package io.dapr.examples.invoke.http;
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.text.DateFormat;
@ -19,6 +14,12 @@ import java.util.Calendar;
import java.util.Map;
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.
*/
@ -35,6 +36,12 @@ public class DemoServiceController {
*/
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")
public Mono<String> handleMethod(@RequestBody(required = false) byte[] body,
@RequestHeader Map<String, String> headers) {
@ -49,7 +56,7 @@ public class DemoServiceController {
// Handles the request by printing message.
System.out.println(
"Server: " + message + " @ " + utcNowAsString + " and metadata: " + metadataString);
"Server: " + message + " @ " + utcNowAsString + " and metadata: " + metadataString);
return utcNowAsString;
} catch (Exception e) {

View File

@ -7,14 +7,14 @@ package io.dapr.examples.invoke.http;
import io.dapr.client.DaprClient;
import io.dapr.client.DaprClientBuilder;
import io.dapr.serializer.DefaultObjectSerializer;
import io.dapr.client.domain.Verb;
/**
* 1. Build and install jars:
* mvn clean install
* 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 {
@ -25,6 +25,7 @@ public class InvokeClient {
/**
* Starts the invoke client.
*
* @param args Messages to be sent as request for the invoke API.
*/
public static void main(String[] args) {

View File

@ -16,7 +16,8 @@ import java.util.Collections;
* 1. Build and install jars:
* mvn clean install
* 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 {
@ -25,6 +26,11 @@ public class Publisher {
//The title of the topic to be used for publishing
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 {
//Creating the DaprClient: Using the default builder client produces an HTTP Dapr Client
DaprClient client = new DaprClientBuilder().build();

View File

@ -16,13 +16,19 @@ import org.apache.commons.cli.Options;
* 1. Build and install jars:
* mvn clean install
* 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 {
/**
* 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 {
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();
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.serializer.DefaultObjectSerializer;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
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.
*/
@ -21,13 +25,19 @@ public class SubscriberController {
/**
* Dapr's default serializer/deserializer.
*/
private static final DefaultObjectSerializer SERIALIZER = new DefaultObjectSerializer ();
private static final DefaultObjectSerializer SERIALIZER = new DefaultObjectSerializer();
@GetMapping("/dapr/subscribe")
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")
public Mono<Void> handleMessage(@RequestBody(required = false) byte[] body,
@RequestHeader Map<String, String> headers) {

View File

@ -4,7 +4,11 @@ import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import io.dapr.DaprGrpc;
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.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
*/
public class Example {
/**
* The main method of this app.
* @param args Not used.
*/
public static void main(String[] args) {
ManagedChannel channel =
ManagedChannelBuilder.forAddress("localhost", 50001).usePlaintext().build();
ManagedChannelBuilder.forAddress("localhost", 50001).usePlaintext().build();
DaprBlockingStub client = DaprGrpc.newBlockingStub(channel);
String key = "mykey";
@ -26,13 +34,13 @@ public class Example {
{
String value = UUID.randomUUID().toString();
StateRequest req = StateRequest
.newBuilder()
.setKey(key)
.setValue(Any.newBuilder().setValue(ByteString.copyFromUtf8(value)).build())
.build();
.newBuilder()
.setKey(key)
.setValue(Any.newBuilder().setValue(ByteString.copyFromUtf8(value)).build())
.build();
SaveStateEnvelope state = SaveStateEnvelope.newBuilder()
.addRequests(req)
.build();
.addRequests(req)
.build();
client.saveState(state);
System.out.println("Saved!");
}
@ -40,9 +48,9 @@ public class Example {
// Now, read it back.
{
GetStateEnvelope req = GetStateEnvelope
.newBuilder()
.setKey(key)
.build();
.newBuilder()
.setKey(key)
.build();
GetStateResponseEnvelope response = client.getState(req);
String value = response.getData().getValue().toStringUtf8();
System.out.println("Got: " + value);
@ -51,9 +59,9 @@ public class Example {
// Then, delete it.
{
DeleteStateEnvelope req = DeleteStateEnvelope
.newBuilder()
.setKey(key)
.build();
.newBuilder()
.setKey(key)
.build();
client.deleteState(req);
System.out.println("Deleted!");
}

View File

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

View File

@ -6,7 +6,13 @@
package io.dapr.springboot;
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;
/**

View File

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

View File

@ -39,7 +39,7 @@ class DaprHttpClient implements DaprClient {
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);
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());
}

View File

@ -36,7 +36,7 @@ class DaprHttpClient implements DaprClient {
@Override
public Mono<byte[]> getActorState(String actorType, String actorId, String 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());
}
@ -46,7 +46,7 @@ class DaprHttpClient implements DaprClient {
@Override
public Mono<Void> saveActorStateTransactionally(String actorType, String actorId, byte[] data) {
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
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);
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
public Mono<Void> unregisterActorReminder(String actorType, String actorId, String 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
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);
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
public Mono<Void> unregisterActorTimer(String actorType, String actorId, String 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.writeStringField("key", stateChange.getStateName());
if ((stateChange.getChangeKind() == ActorStateChangeKind.UPDATE)
|| (stateChange.getChangeKind() == ActorStateChangeKind.ADD)) {
|| (stateChange.getChangeKind() == ActorStateChangeKind.ADD)) {
byte[] data = this.stateSerializer.serialize(stateChange.getValue());
if (data != null) {
if (this.isStateString) {

View File

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

View File

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

View File

@ -2,15 +2,15 @@
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*/
package io.dapr.client;
import io.dapr.client.domain.State;
import io.dapr.client.domain.StateOptions;
import io.dapr.client.domain.Verb;
import reactor.core.publisher.Mono;
import java.util.List;
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.
@ -53,7 +53,8 @@ public interface DaprClient {
* @param <R> The Type of the request, use byte[] to skip serialization.
* @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.

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*/
package io.dapr.client;
import io.dapr.DaprGrpc;
@ -19,108 +20,106 @@ import okhttp3.OkHttpClient;
*/
public class DaprClientBuilder {
/**
* Determine if this builder will create GRPC clients instead of HTTP clients.
*/
private final boolean useGRPC;
/**
* Determine if this builder will create GRPC clients instead of HTTP clients.
*/
private final boolean useGrpc;
/**
* Serializer used for request and response objects in DaprClient.
*/
private DaprObjectSerializer objectSerializer;
/**
* Serializer used for request and response objects in DaprClient.
*/
private DaprObjectSerializer objectSerializer;
/**
* Serializer used for state objects in DaprClient.
*/
private DaprObjectSerializer stateSerializer;
/**
* Serializer used for state objects in DaprClient.
*/
private DaprObjectSerializer stateSerializer;
/**
* Creates a constructor for DaprClient.
*
* {@link DefaultObjectSerializer} is used for object and state serializers by defaul but is not recommended
* for production scenarios.
*/
public DaprClientBuilder() {
this.objectSerializer = new DefaultObjectSerializer();
this.stateSerializer = new DefaultObjectSerializer();
this.useGRPC = Properties.USE_GRPC.get();
/**
* Creates a constructor for DaprClient.
*
* {@link DefaultObjectSerializer} is used for object and state serializers by defaul but is not recommended
* for production scenarios.
*/
public DaprClientBuilder() {
this.objectSerializer = new DefaultObjectSerializer();
this.stateSerializer = new DefaultObjectSerializer();
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");
}
/**
* 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;
return this;
}
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");
}
/**
* 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;
return this;
}
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();
}
/**
* 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();
}
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.
*
* @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 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);
/**
* 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);
}
}

View File

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

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*/
package io.dapr.client;
import io.dapr.client.domain.State;
@ -11,10 +12,16 @@ import io.dapr.serializer.DaprObjectSerializer;
import io.dapr.serializer.DefaultObjectSerializer;
import io.dapr.serializer.StringContentType;
import io.dapr.utils.Constants;
import reactor.core.publisher.Mono;
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.
@ -30,7 +37,7 @@ public class DaprClientHttpAdapter implements DaprClient {
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
*/
@ -98,7 +105,7 @@ public class DaprClientHttpAdapter implements DaprClient {
byte[] serializedEvent = objectSerializer.serialize(event);
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();
} catch (Exception ex) {
return Mono.error(ex);
@ -109,7 +116,8 @@ public class DaprClientHttpAdapter implements DaprClient {
* {@inheritDoc}
*/
@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 {
if (verb == 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);
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 -> {
try {
T object = objectSerializer.deserialize(r.getBody(), clazz);
if (object == null) {
return Mono.empty();
}
try {
T object = objectSerializer.deserialize(r.getBody(), clazz);
if (object == null) {
return Mono.empty();
}
return Mono.just(object);
} catch (Exception ex) {
return Mono.error(ex);
}
});
return Mono.just(object);
} catch (Exception ex) {
return Mono.error(ex);
}
});
} catch (Exception ex) {
return Mono.error(ex);
}
@ -145,7 +153,8 @@ public class DaprClientHttpAdapter implements DaprClient {
* {@inheritDoc}
*/
@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);
}
@ -153,7 +162,8 @@ public class DaprClientHttpAdapter implements DaprClient {
* {@inheritDoc}
*/
@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();
}
@ -161,7 +171,8 @@ public class DaprClientHttpAdapter implements DaprClient {
* {@inheritDoc}
*/
@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();
}
@ -169,7 +180,8 @@ public class DaprClientHttpAdapter implements DaprClient {
* {@inheritDoc}
*/
@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);
}
@ -188,7 +200,7 @@ public class DaprClientHttpAdapter implements DaprClient {
StringBuilder url = new StringBuilder(Constants.BINDING_PATH).append("/").append(name);
return this.client
.invokeAPI(
.invokeApi(
DaprHttp.HttpMethods.POST.name(),
url.toString(),
null,
@ -231,11 +243,14 @@ public class DaprClientHttpAdapter implements DaprClient {
}
StringBuilder url = new StringBuilder(Constants.STATE_PATH)
.append("/")
.append(key);
Map<String, String> urlParameters = Optional.ofNullable(options).map(o -> o.getStateOptionsAsMap() ).orElse(new HashMap<>());;
.append("/")
.append(key);
Map<String, String> urlParameters = Optional.ofNullable(options)
.map(o -> o.getStateOptionsAsMap())
.orElse(new HashMap<>());
return this.client
.invokeAPI(DaprHttp.HttpMethods.GET.name(), url.toString(), urlParameters, headers)
.invokeApi(DaprHttp.HttpMethods.GET.name(), url.toString(), urlParameters, headers)
.flatMap(s -> {
try {
return Mono.just(buildStateKeyValue(s, key, options, clazz));
@ -272,14 +287,14 @@ public class DaprClientHttpAdapter implements DaprClient {
byte[] data = this.stateSerializer.serialize(state.getValue());
if (this.isStateString) {
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 {
internalStateObjects.add(new State<>(data, state.getKey(), state.getEtag(), state.getOptions()));
}
}
byte[] serializedStateBody = INTERNAL_SERIALIZER.serialize(states);
return this.client.invokeAPI(
DaprHttp.HttpMethods.POST.name(), url, null, serializedStateBody, headers).then();
return this.client.invokeApi(
DaprHttp.HttpMethods.POST.name(), url, null, serializedStateBody, headers).then();
} catch (Exception ex) {
return Mono.error(ex);
}
@ -299,7 +314,7 @@ public class DaprClientHttpAdapter implements DaprClient {
@Override
public Mono<Void> saveState(String key, String etag, Object value, StateOptions 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);
}
String url = Constants.STATE_PATH + "/" + key;
Map<String, String> urlParameters = Optional.ofNullable(options).map(stateOptions -> stateOptions.getStateOptionsAsMap()).orElse( new HashMap<>());;
return this.client.invokeAPI(DaprHttp.HttpMethods.DELETE.name(), url, urlParameters, headers).then();
Map<String, String> urlParameters = Optional.ofNullable(options)
.map(stateOptions -> stateOptions.getStateOptionsAsMap())
.orElse(new HashMap<>());
return this.client.invokeApi(DaprHttp.HttpMethods.DELETE.name(), url, urlParameters, headers).then();
} catch (Exception 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 clazz The Class 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.
*/
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.
T value = stateSerializer.deserialize(response.getBody(), clazz);
String key = requestedKey;

View File

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

View File

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

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*/
package io.dapr.client;
import com.fasterxml.jackson.annotation.JsonInclude;
@ -17,114 +18,137 @@ import java.util.Base64;
*/
public class ObjectSerializer {
/**
* Shared Json serializer/deserializer as per Jackson's documentation.
*/
protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setSerializationInclusion(JsonInclude.Include.NON_NULL);
/**
* Shared Json serializer/deserializer as per Jackson's documentation.
*/
protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setSerializationInclusion(JsonInclude.Include.NON_NULL);
/**
* Default constructor to avoid class from being instantiated outside package but still inherited.
*/
protected ObjectSerializer() {
/**
* Default constructor to avoid class from being instantiated outside package but still inherited.
*/
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;
}
/**
* 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) {
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);
if (state.getClass() == Void.class) {
return null;
}
/**
* 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);
// Have this check here to be consistent with deserialization (see deserialize() method below).
if (state instanceof byte[]) {
return (byte[]) state;
}
/**
* 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);
// 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);
}
/**
* 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.
*/
protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setSerializationInclusion(JsonInclude.Include.NON_NULL);
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setSerializationInclusion(JsonInclude.Include.NON_NULL);
/**
* Identifier of the message being processed.
@ -57,20 +57,21 @@ public final class CloudEvent {
/**
* Instantiates a new input request.
* @param id Identifier of the message being processed.
* @param source Source for this event.
* @param type Type of event.
* @param specversion Version of the event spec.
*
* @param id Identifier of the message being processed.
* @param source Source for this event.
* @param type Type of event.
* @param specversion Version of the event spec.
* @param datacontenttype Type of the payload.
* @param data Payload.
* @param data Payload.
*/
public CloudEvent(
String id,
String source,
String type,
String specversion,
String datacontenttype,
String data) {
String id,
String source,
String type,
String specversion,
String datacontenttype,
String data) {
this.id = id;
this.source = source;
this.type = type;
@ -81,6 +82,7 @@ public final class CloudEvent {
/**
* Gets the identifier of the message being processed.
*
* @return Identifier of the message being processed.
*/
public String getId() {
@ -89,6 +91,7 @@ public final class CloudEvent {
/**
* Gets the source for this event.
*
* @return Source for this event.
*/
public String getSource() {
@ -97,6 +100,7 @@ public final class CloudEvent {
/**
* Gets the type of event.
*
* @return Type of event.
*/
public String getType() {
@ -105,6 +109,7 @@ public final class CloudEvent {
/**
* Gets the version of the event spec.
*
* @return Version of the event spec.
*/
public String getSpecversion() {
@ -113,6 +118,7 @@ public final class CloudEvent {
/**
* Gets the type of the payload.
*
* @return Type of the payload.
*/
public String getDatacontenttype() {
@ -120,7 +126,8 @@ public final class CloudEvent {
}
/**
* Gets the payload
* Gets the payload.
*
* @return Payload
*/
public String getData() {
@ -129,15 +136,21 @@ public final class CloudEvent {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CloudEvent that = (CloudEvent) o;
return Objects.equals(id, that.id) &&
Objects.equals(source, that.source) &&
Objects.equals(type, that.type) &&
Objects.equals(specversion, that.specversion) &&
Objects.equals(datacontenttype, that.datacontenttype) &&
Objects.equals(data, that.data);
return Objects.equals(id, that.id)
&& Objects.equals(source, that.source)
&& Objects.equals(type, that.type)
&& Objects.equals(specversion, that.specversion)
&& Objects.equals(datacontenttype, that.datacontenttype)
&& Objects.equals(data, that.data);
}
@Override
@ -147,6 +160,7 @@ public final class CloudEvent {
/**
* Deserialized a message topic from Dapr.
*
* @param payload Payload sent from Dapr.
* @return Message (can be null if input is null)
* @throws IOException If cannot parse.
@ -158,7 +172,7 @@ public final class CloudEvent {
JsonNode node = OBJECT_MAPPER.readTree(payload);
if (node== null) {
if (node == null) {
return null;
}

View File

@ -2,19 +2,21 @@
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*/
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
*/
public class State<T> {
/**
* The value of the state
* The value of the state.
*/
private final T value;
/**
* The key of the state
* The key of the state.
*/
private final String key;
/**
@ -24,15 +26,17 @@ public class State<T> {
private final String etag;
/**
* The options used for saving the state
* The options used for saving the state.
*/
private final StateOptions options;
/**
* Create an inmutable state
* This Constructor MUST be used anytime you need to retrieve or delete a 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.
*/
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.
* @param value - The value 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 value - The value 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 redis)
* only numbers are supported.
* @param options - REQUIRED when saving a state.
*/
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
*/
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
*/
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
*/
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
*/
public StateOptions getOptions() {
@ -91,15 +101,31 @@ public class State<T> {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof State)) return false;
if (this == o) {
return true;
}
if (!(o instanceof State)) {
return false;
}
State<?> that = (State<?>) o;
if (getValue() != null ? !getValue().equals(that.getValue()) : that.getValue() != 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;
if (getValue() != null ? !getValue().equals(that.getValue()) : that.getValue() != 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;
}
@ -115,11 +141,11 @@ public class State<T> {
@Override
public String toString() {
return "StateKeyValue{" +
"value=" + value +
", key='" + key + "'" +
", etag='" + etag + "'" +
", options={'" + options.toString() + "}" +
"}";
return "StateKeyValue{"
+ "value=" + value
+ ", key='" + key + "'"
+ ", etag='" + etag + "'"
+ ", options={'" + options.toString() + "}"
+ "}";
}
}

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*/
package io.dapr.client.domain;
import com.fasterxml.jackson.annotation.JsonCreator;
@ -20,7 +21,6 @@ import io.dapr.utils.DurationUtils;
import java.io.IOException;
import java.time.Duration;
import java.time.temporal.TemporalUnit;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@ -31,6 +31,12 @@ public class StateOptions {
private final Concurrency concurrency;
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) {
this.consistency = consistency;
this.concurrency = concurrency;
@ -49,6 +55,10 @@ public class StateOptions {
return retryPolicy;
}
/**
* Returns state options as a Map of option name to value.
* @return A map of state options.
*/
@JsonIgnore
public Map<String, String> getStateOptionsAsMap() {
Map<String, String> mapOptions = null;
@ -98,7 +108,7 @@ public class StateOptions {
public enum Concurrency {
FIRST_WRITE("first-write"),
LAST_WRITE ("last-write");
LAST_WRITE("last-write");
private final String value;
@ -146,6 +156,12 @@ public class StateOptions {
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) {
this.interval = interval;
this.threshold = threshold;
@ -171,12 +187,16 @@ public class StateOptions {
super(Duration.class);
}
public StateOptionDurationSerializer(Class<Duration> t) {
super(t);
}
@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());
}
}
@ -187,12 +207,14 @@ public class StateOptions {
}
@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);
Duration duration = null;
if (durationStr != null && !durationStr.trim().isEmpty()) {
try {
duration = DurationUtils.ConvertDurationFromDaprFormat(durationStr);
duration = DurationUtils.convertDurationFromDaprFormat(durationStr);
} catch (Exception ex) {
throw InvalidFormatException.from(jsonParser, "Unable to parse duration.", ex);
}

View File

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

View File

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

View File

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

View File

@ -5,13 +5,17 @@
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.
*
* This information can be used to at the state store, for example, to save serialized data as plain text.
*/
@Documented
@Target({ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)

View File

@ -2,6 +2,7 @@
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
*/
package io.dapr.utils;
/**
@ -9,73 +10,73 @@ package io.dapr.utils;
*/
public final class Constants {
/**
* Dapr API used in this client.
*/
public static final String API_VERSION = "v1.0";
/**
* Dapr API used in this client.
*/
public static final String API_VERSION = "v1.0";
/**
* Dapr's default hostname.
*/
public static final String DEFAULT_HOSTNAME = "localhost";
/**
* Dapr's default hostname.
*/
public static final String DEFAULT_HOSTNAME = "localhost";
/**
* Header used for request id in Dapr.
*/
public static final String HEADER_DAPR_REQUEST_ID = "X-DaprRequestId";
/**
* Header used for request id in Dapr.
*/
public static final String HEADER_DAPR_REQUEST_ID = "X-DaprRequestId";
/**
* Header for the conditional operation.
*/
public static final String HEADER_HTTP_ETAG_ID = "If-Match";
/**
* Header for the conditional operation.
*/
public static final String HEADER_HTTP_ETAG_ID = "If-Match";
/**
* Base URL for Dapr Actor APIs.
*/
private static final String ACTORS_BASE_URL = API_VERSION + "/" + "actors";
/**
* Base URL for Dapr Actor APIs.
*/
private static final String ACTORS_BASE_URL = API_VERSION + "/" + "actors";
/**
* 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";
/**
* 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";
/**
* String format for Actors state management relative url.
*/
public static final String ACTOR_STATE_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/state";
/**
* String format for Actors state management relative url.
*/
public static final String ACTOR_STATE_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/state";
/**
* String format for Actors method invocation relative url.
*/
public static final String ACTOR_METHOD_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/method/%s";
/**
* String format for Actors method invocation relative url.
*/
public static final String ACTOR_METHOD_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/method/%s";
/**
* String format for Actors reminder registration relative url..
*/
public static final String ACTOR_REMINDER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/reminders/%s";
/**
* String format for Actors reminder registration relative url..
*/
public static final String ACTOR_REMINDER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/reminders/%s";
/**
* String format for Actors timer registration relative url..
*/
public static final String ACTOR_TIMER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/timers/%s";
/**
* String format for Actors timer registration relative url..
*/
public static final String ACTOR_TIMER_RELATIVE_URL_FORMAT = ACTORS_BASE_URL + "/%s/%s/timers/%s";
/**
* Base path to invoke methods.
*/
public static final String INVOKE_PATH = API_VERSION + "/invoke";
/**
* Base path to invoke methods.
*/
public static final String INVOKE_PATH = API_VERSION + "/invoke";
/**
* Invoke Publish Path
*/
public static final String PUBLISH_PATH = API_VERSION + "/publish";
/**
* Invoke Publish Path.
*/
public static final String PUBLISH_PATH = API_VERSION + "/publish";
/**
* Invoke Binding Path
*/
public static final String BINDING_PATH = API_VERSION + "/bindings";
/**
* Invoke Binding Path.
*/
public static final String BINDING_PATH = API_VERSION + "/bindings";
/**
* State Path
*/
public static final String STATE_PATH = API_VERSION + "/state";
/**
* State Path.
*/
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).
* @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
// An example of the format is: 4h15m50s60ms. It does not include days.
int hIndex = valueString.indexOf('h');
int mIndex = valueString.indexOf('m');
int sIndex = valueString.indexOf('s');
int msIndex = valueString.indexOf("ms");
int hourIndex = valueString.indexOf('h');
int minuteIndex = valueString.indexOf('m');
int secondIndex = valueString.indexOf('s');
int milliIndex = valueString.indexOf("ms");
String hoursSpan = valueString.substring(0, hIndex);
String hoursSpan = valueString.substring(0, hourIndex);
int hours = Integer.parseInt(hoursSpan);
int days = hours / 24;
hours = hours % 24;
String minutesSpan = valueString.substring(hIndex + 1, mIndex);
String minutesSpan = valueString.substring(hourIndex + 1, minuteIndex);
int minutes = Integer.parseInt(minutesSpan);
String secondsSpan = valueString.substring(mIndex + 1, sIndex);
String secondsSpan = valueString.substring(minuteIndex + 1, secondIndex);
int seconds = Integer.parseInt(secondsSpan);
String millisecondsSpan = valueString.substring(sIndex + 1, msIndex);
String millisecondsSpan = valueString.substring(secondIndex + 1, milliIndex);
int milliseconds = Integer.parseInt(millisecondsSpan);
return Duration.ZERO
@ -52,13 +52,13 @@ public class DurationUtils {
* @param value Duration
* @return The Duration formatted as a String in the format the Dapr runtime uses (e.g. 4h15m50s60ms)
*/
public static String ConvertDurationToDaprFormat(Duration value) {
public static String convertDurationToDaprFormat(Duration value) {
String stringValue = "";
// return empty string for anything negative, it'll only happen for reminder "periods", not dueTimes. A
// negative "period" means fire once only.
if (value == Duration.ZERO ||
(value.compareTo(Duration.ZERO) == 1)) {
if (value == Duration.ZERO
|| (value.compareTo(Duration.ZERO) == 1)) {
long hours = getDaysPart(value) * 24 + getHoursPart(value);
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
* @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.
*/
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.
*/
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.
*/
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.

View File

@ -32,7 +32,7 @@ public class DaprHttpStub extends DaprHttp {
* @return
*/
@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();
}
@ -40,7 +40,7 @@ public class DaprHttpStub extends DaprHttp {
* {@inheritDoc}
*/
@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();
}
@ -48,7 +48,7 @@ public class DaprHttpStub extends DaprHttp {
* {@inheritDoc}
*/
@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();
}
}

View File

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

View File

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

View File

@ -10,9 +10,9 @@ public class DurationUtilsTest {
@Test
public void convertTimeBothWays() {
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);
}
@ -20,16 +20,16 @@ public class DurationUtilsTest {
public void largeHours() {
// hours part is larger than 24
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);
}
@Test
public void negativeDuration() {
Duration d = Duration.ofSeconds(-99);
String t = DurationUtils.ConvertDurationToDaprFormat(d);
String t = DurationUtils.convertDurationToDaprFormat(d);
Assert.assertEquals("", t);
}