mirror of
https://github.com/heroiclabs/nakama-java.git
synced 2026-11-24 08:55:49 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ec9b27cdf | ||
|
|
32a2a01325 | ||
|
|
a98c6cb998 |
No files matched your search
@@ -6,6 +6,21 @@ The format is based on [keep a changelog](http://keepachangelog.com/) and this p
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.3.0] - 2023-07-18
|
||||
|
||||
### Added
|
||||
- Satori: Adds HTTP support to the Satori client via using the `HttpClient` instead of the grpc-based `DefaultClient`.
|
||||
- Satori: Added ability to specify default flag value in `GetFlag` calls.
|
||||
|
||||
### Fixed
|
||||
- Satori: Fixed handling of network errors when calling `GetDefaultFlag` and returning of default flag value in such cases.
|
||||
|
||||
## [2.2.1] - 2023-07-07
|
||||
### Fixed
|
||||
- Fixed packing of external dependencies into fat jars.
|
||||
- Removed unnecessary generated protobuf code from Satori, resulting in a smaller .jar file.
|
||||
- Fixed links to documentation in pom.xml.
|
||||
|
||||
## [2.2.0] - 2023-07-06
|
||||
### Added
|
||||
- Adds the Satori Java SDK. Satori is our liveops server for game studios. Please read more about it on the Heroic Labs website.
|
||||
|
||||
@@ -179,8 +179,9 @@ import com.heroiclabs.satori;
|
||||
Client client = new DefaultClient("https", "your.host.here", 443, "yourApiKey");
|
||||
```
|
||||
|
||||
Then authenticate with the server to obtain your session.
|
||||
Alternatively, for HTTP support rather than gRPC you can create an `HttpClient` with the same parameters.
|
||||
|
||||
Then authenticate with the server to obtain your session.
|
||||
|
||||
```java
|
||||
// Authenticate with the Satori server.
|
||||
|
||||
+18
-15
@@ -47,7 +47,7 @@ lombok {
|
||||
}
|
||||
|
||||
group = 'com.github.heroiclabs'
|
||||
version = '2.2.0'
|
||||
version = '2.3.0'
|
||||
|
||||
sourceCompatibility = 1.8
|
||||
targetCompatibility = 1.8
|
||||
@@ -62,10 +62,6 @@ repositories {
|
||||
}
|
||||
|
||||
configurations {
|
||||
all {
|
||||
exclude group: 'io.grpc', module:'grpc-protobuf'
|
||||
exclude group: 'com.google.protobuf', module: 'protobuf-java'
|
||||
}
|
||||
sharedProtobuf.extendsFrom protobuf
|
||||
sharedApi.extendsFrom api
|
||||
sharedImplementation.extendsFrom implementation
|
||||
@@ -77,10 +73,11 @@ dependencies {
|
||||
shadow gradleApi()
|
||||
|
||||
implementation 'com.google.code.gson:gson:2.8.9'
|
||||
api 'io.grpc:grpc-protobuf-lite:1.43.2'
|
||||
api 'io.grpc:grpc-protobuf:1.43.2'
|
||||
// listenable future is part of the SDK public API
|
||||
api 'com.google.guava:guava:31.0.1-android'
|
||||
implementation 'com.google.protobuf:protobuf-javalite:3.19.3'
|
||||
implementation 'com.google.protobuf:protobuf-java:3.19.6'
|
||||
implementation 'com.google.protobuf:protobuf-java-util:3.19.6'
|
||||
|
||||
implementation('io.grpc:grpc-okhttp:1.48.0') {
|
||||
exclude group: 'com.squareup.okio', module:'okio'
|
||||
@@ -124,6 +121,8 @@ sourceSets {
|
||||
satori {
|
||||
java {
|
||||
srcDirs 'src/satori/java'
|
||||
srcDirs += 'build/generated/source/proto/satori/java'
|
||||
srcDirs += 'build/generated/source/proto/satori/grpc'
|
||||
compileClasspath += configurations.sharedImplementation
|
||||
compileClasspath += configurations.sharedApi
|
||||
compileClasspath += configurations.sharedProtobuf
|
||||
@@ -135,6 +134,8 @@ sourceSets {
|
||||
proto {
|
||||
srcDir 'src/main/proto'
|
||||
exclude "apigrpc.proto"
|
||||
exclude "github.com/heroiclabs/nakama-common/api/*.proto"
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,13 +174,11 @@ protobuf {
|
||||
generateProtoTasks {
|
||||
all().each { task ->
|
||||
task.builtins {
|
||||
java {
|
||||
option 'lite'
|
||||
}
|
||||
java {}
|
||||
}
|
||||
|
||||
task.plugins {
|
||||
grpc { option 'lite' }
|
||||
grpc {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -246,7 +245,7 @@ publishing {
|
||||
def root = asNode()
|
||||
root.appendNode('description', 'Java client for Nakama server.')
|
||||
root.appendNode('name', 'Nakama client')
|
||||
root.appendNode('url', 'https://heroiclabs.com/docs/android-java-client-guide/') // TODO update this
|
||||
root.appendNode('url', 'https://heroiclabs.com/docs/satori/client-libraries/java/')
|
||||
|
||||
def dependenciesNode = root.appendNode('dependencies')
|
||||
configurations.implementation.allDependencies.each {
|
||||
@@ -270,7 +269,7 @@ publishing {
|
||||
def root = asNode()
|
||||
root.appendNode('description', 'Java client for Satori server.')
|
||||
root.appendNode('name', 'Satori client')
|
||||
root.appendNode('url', 'https://heroiclabs.com/docs/android-java-client-guide/') // TODO update this
|
||||
root.appendNode('url', 'https://heroiclabs.com/docs/satori/client-libraries/java/')
|
||||
|
||||
def dependenciesNode = root.appendNode('dependencies')
|
||||
configurations.implementation.allDependencies.each {
|
||||
@@ -297,14 +296,18 @@ task satoriTest(type: Test) {
|
||||
}
|
||||
|
||||
task nakamaShadowJar(type: ShadowJar) {
|
||||
configurations = [project.configurations.sharedImplementation,
|
||||
project.configurations.sharedApi,
|
||||
project.configurations.sharedProtobuf]
|
||||
from sourceSets.nakama.output
|
||||
configurations = [configurations.sharedImplementation, configurations.sharedApi, configurations.sharedProtobuf]
|
||||
archiveFileName.set("nakama-java-${version}-all.jar")
|
||||
}
|
||||
|
||||
task satoriShadowJar(type: ShadowJar) {
|
||||
configurations = [project.configurations.sharedImplementation,
|
||||
project.configurations.sharedApi,
|
||||
project.configurations.sharedProtobuf]
|
||||
from sourceSets.satori.output
|
||||
configurations = [configurations.sharedImplementation, configurations.sharedApi, configurations.sharedProtobuf]
|
||||
archiveFileName.set("satori-java-${version}-all.jar")
|
||||
}
|
||||
|
||||
|
||||
@@ -88,6 +88,15 @@ public interface Client {
|
||||
*/
|
||||
ListenableFuture<ExperimentList> getExperiments(@NonNull final Session session, @NonNull final String... names);
|
||||
|
||||
/**
|
||||
* Get a single flag for this identity.
|
||||
* @param session The session of the user.
|
||||
* @param name The name of the flag.
|
||||
* @param defaultValue The default value if the server is unreachable or the flag does not exist.
|
||||
* @return A future which resolves to a single feature flag.
|
||||
*/
|
||||
ListenableFuture<Flag> getFlag(@NonNull Session session, @NonNull final String name, @NonNull final String defaultValue);
|
||||
|
||||
/**
|
||||
* Get a single flag for this identity.
|
||||
* @param session The session of the user.
|
||||
@@ -126,7 +135,7 @@ public interface Client {
|
||||
* value specified and will not raise an exception if the network is unreachable.
|
||||
*
|
||||
* @param name The name of the flag.
|
||||
* @param defaultValue The default value if the server is unreachable.
|
||||
* @param defaultValue The default value if the server is unreachable or the flag does not exist.
|
||||
* @return A ListenableFuture which resolves to a single default feature flag.
|
||||
*/
|
||||
ListenableFuture<Flag> getFlagDefault(@NonNull final String name, @NonNull final String defaultValue);
|
||||
|
||||
@@ -181,13 +181,33 @@ public class DefaultClient implements Client {
|
||||
ListenableFuture<FlagList> futureFlagsList = getFlags(session, name);
|
||||
return Futures.transform(futureFlagsList, flagList -> {
|
||||
if (flagList.getFlagsList().size() == 1) {
|
||||
flagList.getFlagsList().get(0);
|
||||
return flagList.getFlagsList().get(0);
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Flag '" + name + "' not found.");
|
||||
}, MoreExecutors.directExecutor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Flag> getFlag(@NonNull final Session session, @NonNull final String name, @NonNull final String defaultValue) {
|
||||
ListenableFuture<FlagList> futureFlagsList = getFlags(session, name);
|
||||
|
||||
futureFlagsList = Futures.catching(futureFlagsList, Throwable.class, throwable -> {
|
||||
FlagList.Builder flagListBuilder = FlagList.newBuilder();
|
||||
flagListBuilder.addFlags(Flag.newBuilder().setName(name).setValue(defaultValue).build());
|
||||
return flagListBuilder.build();
|
||||
}, MoreExecutors.directExecutor());
|
||||
|
||||
return Futures.transform(futureFlagsList, flagList -> {
|
||||
if (flagList.getFlagsList().size() == 1) {
|
||||
return flagList.getFlagsList().get(0);
|
||||
}
|
||||
|
||||
Flag.Builder builder = Flag.newBuilder();
|
||||
return builder.setName(name).setValue(defaultValue).build();
|
||||
}, MoreExecutors.directExecutor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<FlagList> getFlags(@NonNull final Session session, String... names) {
|
||||
return getStub(session).getFlags(GetFlagsRequest.newBuilder()
|
||||
@@ -200,7 +220,7 @@ public class DefaultClient implements Client {
|
||||
ListenableFuture<FlagList> futureFlagsList = getFlagsDefault(name);
|
||||
return Futures.transform(futureFlagsList, flagList -> {
|
||||
if (flagList.getFlagsList().size() == 1) {
|
||||
flagList.getFlagsList().get(0);
|
||||
return flagList.getFlagsList().get(0);
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Flag '" + name + "' not found.");
|
||||
@@ -210,9 +230,16 @@ public class DefaultClient implements Client {
|
||||
@Override
|
||||
public ListenableFuture<Flag> getFlagDefault(@NonNull String name, @NonNull String defaultValue) {
|
||||
ListenableFuture<FlagList> futureFlagsList = getFlagsDefault(name);
|
||||
|
||||
futureFlagsList = Futures.catching(futureFlagsList, Throwable.class, throwable -> {
|
||||
FlagList.Builder flagListBuilder = FlagList.newBuilder();
|
||||
flagListBuilder.addFlags(Flag.newBuilder().setName(name).setValue(defaultValue).build());
|
||||
return flagListBuilder.build();
|
||||
}, MoreExecutors.directExecutor());
|
||||
|
||||
return Futures.transform(futureFlagsList, flagList -> {
|
||||
if (flagList.getFlagsList().size() == 1) {
|
||||
flagList.getFlagsList().get(0);
|
||||
return flagList.getFlagsList().get(0);
|
||||
}
|
||||
|
||||
Flag.Builder builder = Flag.newBuilder();
|
||||
@@ -220,7 +247,6 @@ public class DefaultClient implements Client {
|
||||
}, MoreExecutors.directExecutor());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ListenableFuture<FlagList> getFlagsDefault(String... names) {
|
||||
return getStub().getFlags(GetFlagsRequest.newBuilder().addAllNames(Arrays.asList(names)).build());
|
||||
|
||||
@@ -0,0 +1,428 @@
|
||||
/*
|
||||
* Copyright 2023 The Satori Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.heroiclabs.satori;
|
||||
|
||||
import com.google.common.io.BaseEncoding;
|
||||
import com.google.common.util.concurrent.Futures;
|
||||
import com.google.common.util.concurrent.ListenableFuture;
|
||||
import com.google.common.util.concurrent.MoreExecutors;
|
||||
import com.google.common.util.concurrent.SettableFuture;
|
||||
import com.google.protobuf.Empty;
|
||||
import com.google.protobuf.InvalidProtocolBufferException;
|
||||
import com.google.protobuf.Message;
|
||||
import com.google.protobuf.Timestamp;
|
||||
import com.google.protobuf.util.JsonFormat;
|
||||
import com.heroiclabs.satori.api.*;
|
||||
import com.heroiclabs.satori.api.Properties;
|
||||
import io.grpc.okhttp.OkHttpChannelBuilder;
|
||||
import kotlin.Pair;
|
||||
import lombok.NonNull;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import okhttp3.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Slf4j
|
||||
public class HttpClient implements Client {
|
||||
|
||||
private final OkHttpClient client;
|
||||
|
||||
private final String basicAuth;
|
||||
private final HttpUrl url;
|
||||
|
||||
private final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
|
||||
private static final String USERAGENT = "satori-java-client";
|
||||
|
||||
/**
|
||||
* A client to interact with the Satori server.
|
||||
* @param apiKey The key used to authenticate with the server without a session.
|
||||
* @param host The host address of the server. Defaults to "127.0.0.1".
|
||||
* @param port The port number of the server. Defaults to 7349.
|
||||
* @param ssl Set connection strings to use the secure mode with the server. Defaults to false. The server must be configured
|
||||
* with an SSL certificate or use a load balancer which performs SSL termination.
|
||||
*/
|
||||
public HttpClient(@NonNull final String apiKey, @NonNull final String host, final int port, final boolean ssl) {
|
||||
this(apiKey, host, port, ssl, 10_000, 0, 0L);
|
||||
}
|
||||
|
||||
/**
|
||||
* A client to interact with the Satori server.
|
||||
* @param apiKey The key used to authenticate with the server without a session.
|
||||
* @param host The host address of the server.
|
||||
* @param port The port number of the server. Defaults to 7349.
|
||||
* @param ssl Set connection strings to use the secure mode with the server. Defaults to false. The server must be configured to make use of this option. The server must
|
||||
* be configured with an SSL certificate or use a load balancer which performs SSL termination.
|
||||
* @param connectTimeoutMs Sets the default connect timeout for new connections. A value of 0 means no timeout, otherwise values must be between 1 and {@code Integer.MAX_VALUE} when converted to milliseconds.
|
||||
* The default value is 10 seconds.
|
||||
* @param callTimeoutMs Sets the default timeout for complete calls. A value of 0 means no timeout, otherwise values must be between 1 and {@code Integer.MAX_VALUE} when converted to milliseconds.
|
||||
* @param pingIntervalMs Sets the interval between HTTP/2 pings initiated by this client. Use this to automatically send ping frames until either the connection fails or it is closed.
|
||||
* This keeps the connection alive and may detect connectivity failures. The default value of 0 disables client-initiated pings.
|
||||
*/
|
||||
public HttpClient(@NonNull final String apiKey, @NonNull final String host, final int port, final boolean ssl,
|
||||
final int connectTimeoutMs, final int callTimeoutMs, final long pingIntervalMs) {
|
||||
String scheme = ssl ? "https" : "http";
|
||||
this.url = new HttpUrl.Builder()
|
||||
.scheme(scheme)
|
||||
.host(host)
|
||||
.port(port)
|
||||
.build();
|
||||
|
||||
this.client = new OkHttpClient.Builder()
|
||||
.connectTimeout(connectTimeoutMs, TimeUnit.MILLISECONDS)
|
||||
.callTimeout(callTimeoutMs, TimeUnit.MILLISECONDS)
|
||||
.pingInterval(pingIntervalMs, TimeUnit.MILLISECONDS)
|
||||
.build();
|
||||
|
||||
final String base64Auth = BaseEncoding.base64().encode((apiKey + ":").getBytes());
|
||||
this.basicAuth = "Basic " + base64Auth;
|
||||
}
|
||||
|
||||
private SatoriGrpc.SatoriFutureStub getStub() {
|
||||
return SatoriGrpc.newFutureStub(OkHttpChannelBuilder.forAddress("", 0).build());
|
||||
}
|
||||
|
||||
private SatoriGrpc.SatoriFutureStub getStub(Session session) {
|
||||
return SatoriGrpc.newFutureStub(OkHttpChannelBuilder.forAddress("", 0).build());
|
||||
}
|
||||
|
||||
private Request request(final Session session) {
|
||||
String authValue = session != null ? "Bearer " + session.getAuthToken() : this.basicAuth;
|
||||
|
||||
return new Request.Builder()
|
||||
.header("authorization", authValue)
|
||||
.header("User-Agent", USERAGENT)
|
||||
.url(url)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Session> authenticate(@NonNull final String id, final Map<String, String> defaultProperties,
|
||||
final Map<String, String> customProperties) {
|
||||
AuthenticateRequest authRequest = AuthenticateRequest.newBuilder()
|
||||
.setId(id)
|
||||
.putAllDefault(defaultProperties)
|
||||
.putAllCustom(customProperties)
|
||||
.build();
|
||||
return call(null, "POST", authRequest, "v1/authenticate", com.heroiclabs.satori.api.Session.newBuilder(), sessionConverter);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Empty> authenticateLogout(@NonNull final Session session) {
|
||||
AuthenticateLogoutRequest logoutRequest = AuthenticateLogoutRequest.newBuilder()
|
||||
.setToken(session.getAuthToken())
|
||||
.setRefreshToken(session.getRefreshToken())
|
||||
.build();
|
||||
|
||||
return post(session, logoutRequest, "v1/authenticate/logout", Empty.newBuilder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Empty> event(@NonNull final Session session, @NonNull final Event event) {
|
||||
EventRequest eventRequest = EventRequest.newBuilder()
|
||||
.addEvents(toProtoEvent(event))
|
||||
.build();
|
||||
|
||||
return post(session, eventRequest, "v1/event", Empty.newBuilder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Empty> events(@NonNull final Session session, @NonNull final List<Event> events) {
|
||||
EventRequest.Builder builder = EventRequest.newBuilder();
|
||||
|
||||
for (Event event : events) {
|
||||
builder.addEvents(toProtoEvent(event));
|
||||
}
|
||||
|
||||
return post(session, builder.build(), "v1/event", Empty.newBuilder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<ExperimentList> getAllExperiments(@NonNull final Session session) {
|
||||
return get(session, "v1/experiment", Collections.emptyList(), ExperimentList.newBuilder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<ExperimentList> getExperiments(@NonNull final Session session, @NonNull final String... names) {
|
||||
List<Pair<String, String>> params = new ArrayList<>();
|
||||
for (String name : names) {
|
||||
params.add(new Pair<>("names", name));
|
||||
}
|
||||
return get(session, "v1/experiment", params, ExperimentList.newBuilder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Flag> getFlag(@NonNull final Session session, @NonNull final String name) {
|
||||
ListenableFuture<FlagList> futureFlagsList = getFlags(session, name);
|
||||
return Futures.transform(futureFlagsList, flagList -> {
|
||||
if (flagList.getFlagsList().size() == 1) {
|
||||
return flagList.getFlagsList().get(0);
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Flag '" + name + "' not found.");
|
||||
}, MoreExecutors.directExecutor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Flag> getFlag(@NonNull final Session session, @NonNull final String name, @NonNull final String defaultValue) {
|
||||
ListenableFuture<FlagList> futureFlagsList = getFlags(session, name);
|
||||
|
||||
futureFlagsList = Futures.catching(futureFlagsList, Throwable.class, throwable -> {
|
||||
FlagList.Builder flagListBuilder = FlagList.newBuilder();
|
||||
flagListBuilder.addFlags(Flag.newBuilder().setName(name).setValue(defaultValue).build());
|
||||
return flagListBuilder.build();
|
||||
}, MoreExecutors.directExecutor());
|
||||
|
||||
return Futures.transform(futureFlagsList, flagList -> {
|
||||
if (flagList.getFlagsList().size() == 1) {
|
||||
return flagList.getFlagsList().get(0);
|
||||
}
|
||||
|
||||
Flag.Builder builder = Flag.newBuilder();
|
||||
return builder.setName(name).setValue(defaultValue).build();
|
||||
}, MoreExecutors.directExecutor());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ListenableFuture<FlagList> getFlags(@NonNull final Session session, String... names) {
|
||||
List<Pair<String, String>> params = new ArrayList<>();
|
||||
for (String name : names) {
|
||||
params.add(new Pair<>("names", name));
|
||||
}
|
||||
return get(session, "v1/flag", params, FlagList.newBuilder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Flag> getFlagDefault(@NonNull String name) {
|
||||
ListenableFuture<FlagList> futureFlagsList = getFlagsDefault(name);
|
||||
|
||||
return Futures.transform(futureFlagsList, flagList -> {
|
||||
if (flagList.getFlagsList().size() == 1) {
|
||||
return flagList.getFlagsList().get(0);
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Flag '" + name + "' not found.");
|
||||
}, MoreExecutors.directExecutor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Flag> getFlagDefault(@NonNull String name, @NonNull String defaultValue) {
|
||||
ListenableFuture<FlagList> futureFlagsList = getFlagsDefault(name);
|
||||
futureFlagsList = Futures.catching(futureFlagsList, Throwable.class, throwable -> {
|
||||
FlagList.Builder flagListBuilder = FlagList.newBuilder();
|
||||
flagListBuilder.addFlags(Flag.newBuilder().setName(name).setValue(defaultValue).build());
|
||||
return flagListBuilder.build();
|
||||
}, MoreExecutors.directExecutor());
|
||||
|
||||
return Futures.transform(futureFlagsList, flagList -> {
|
||||
if (flagList.getFlagsList().size() == 1) {
|
||||
return flagList.getFlagsList().get(0);
|
||||
}
|
||||
|
||||
Flag.Builder builder = Flag.newBuilder();
|
||||
return builder.setName(name).setValue(defaultValue).build();
|
||||
}, MoreExecutors.directExecutor());
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ListenableFuture<FlagList> getFlagsDefault(String... names) {
|
||||
List<Pair<String, String>> params = new ArrayList<>();
|
||||
for (String name : names) {
|
||||
params.add(new Pair<>("names", name));
|
||||
}
|
||||
return get(null, "v1/flag", params, FlagList.newBuilder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<LiveEventList> getLiveEvents(@NonNull final Session session, String... names) {
|
||||
List<Pair<String, String>> params = new ArrayList<>();
|
||||
for (String name : names) {
|
||||
params.add(new Pair<>("names", name));
|
||||
}
|
||||
return get(session, "v1/live-event", params, LiveEventList.newBuilder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Empty> updateProperties(@NonNull final Session session, @NonNull final Map<String, String> defaultProperties, @NonNull final Map<String, String> customProperties) {
|
||||
// Assuming we have a method to convert Properties to a Map
|
||||
UpdatePropertiesRequest updatePropertiesRequest = UpdatePropertiesRequest.newBuilder()
|
||||
.putAllDefault(defaultProperties)
|
||||
.putAllCustom(customProperties)
|
||||
.build();
|
||||
return put(session, updatePropertiesRequest, "v1/properties", Empty.newBuilder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Empty> deleteIdentity(@NonNull final Session session) {
|
||||
return delete(session, Empty.newBuilder().build(), "v1/identity", Empty.newBuilder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnect() {
|
||||
this.client.dispatcher().executorService().shutdown();
|
||||
this.client.connectionPool().evictAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnect(final long timeout, @NonNull final TimeUnit unit) throws InterruptedException {
|
||||
disconnect();
|
||||
this.client.dispatcher().executorService().awaitTermination(timeout, unit);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Properties> listProperties(@NonNull Session session) {
|
||||
return get(session, "v1/properties", Collections.emptyList(), Properties.newBuilder());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Session> identify(@NonNull Session session, @NonNull String id,
|
||||
@NonNull Map<String, String> defaultProperties, @NonNull Map<String, String> customProperties) {
|
||||
IdentifyRequest identifyRequest = IdentifyRequest.newBuilder().setId(id).build();
|
||||
return call(session, "PUT", identifyRequest, "v1/identify", com.heroiclabs.satori.api.Session.newBuilder(), sessionConverter);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public ListenableFuture<Session> sessionRefresh(Session session) {
|
||||
AuthenticateRefreshRequest authenticateRefreshRequest = AuthenticateRefreshRequest.newBuilder().setRefreshToken(session.getRefreshToken()).build();
|
||||
return call(session, "POST", authenticateRefreshRequest, "v1/authenticate/refresh", com.heroiclabs.satori.api.Session.newBuilder(), sessionConverter);
|
||||
}
|
||||
|
||||
private Timestamp toProtoTimestamp(Instant instant) {
|
||||
return Timestamp.newBuilder()
|
||||
.setSeconds(instant.getEpochSecond())
|
||||
.setNanos(instant.getNano())
|
||||
.build();
|
||||
}
|
||||
|
||||
private com.heroiclabs.satori.api.Event toProtoEvent(Event event) {
|
||||
com.heroiclabs.satori.api.Event.Builder eventBuilder = com.heroiclabs.satori.api.Event.newBuilder();
|
||||
eventBuilder
|
||||
.setName(event.getName())
|
||||
.setValue(event.getValue())
|
||||
.setTimestamp(toProtoTimestamp(event.getTimestamp()))
|
||||
.putAllMetadata(event.getMetadata());
|
||||
|
||||
return eventBuilder.build();
|
||||
}
|
||||
|
||||
private final Function<com.heroiclabs.satori.api.Session, Session> sessionConverter = (input)
|
||||
-> new DefaultSession(input.getToken(), input.getRefreshToken());
|
||||
|
||||
private <T extends Message> ListenableFuture<T> post(Session session, Message requestBody, String path, T.Builder responseBuilder) {
|
||||
return call(session, "POST", requestBody, path, responseBuilder, Function.identity());
|
||||
}
|
||||
|
||||
private <T extends Message> ListenableFuture<T> put(Session session, Message requestBody, String path, T.Builder responseBuilder) {
|
||||
return call(session, "PUT", requestBody, path, responseBuilder, Function.identity());
|
||||
}
|
||||
|
||||
private <T extends Message> ListenableFuture<T> delete(Session session, Message requestBody, String path, T.Builder responseBuilder) {
|
||||
return call(session, "DELETE", requestBody, path, responseBuilder, Function.identity());
|
||||
}
|
||||
|
||||
private <T extends Message, O> ListenableFuture<O> call(Session session, String method, Message requestBody, String path, T.Builder responseBuilder, Function<T, O> responseConverter) {
|
||||
SettableFuture<O> future = SettableFuture.create();
|
||||
String body;
|
||||
try {
|
||||
body = JsonFormat.printer().print(requestBody);
|
||||
} catch (InvalidProtocolBufferException e) {
|
||||
future.setException(e);
|
||||
return future;
|
||||
}
|
||||
Request.Builder reqBuilder = request(session).newBuilder()
|
||||
.url(url.newBuilder().addPathSegments(path).build());
|
||||
|
||||
switch (method) {
|
||||
case "POST":
|
||||
reqBuilder.post(RequestBody.create(body, JSON));
|
||||
break;
|
||||
case "PUT":
|
||||
reqBuilder.put(RequestBody.create(body, JSON));
|
||||
break;
|
||||
case "DELETE":
|
||||
reqBuilder.delete(RequestBody.create(body, JSON));
|
||||
break;
|
||||
default:
|
||||
future.setException(new IllegalArgumentException("Unknown method: "+method));
|
||||
return future;
|
||||
}
|
||||
|
||||
Request request = reqBuilder.build();
|
||||
|
||||
client.newCall(request).enqueue(new Callback() {
|
||||
@Override
|
||||
public void onFailure(Call call, IOException e) {
|
||||
future.setException(e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResponse(Call call, final Response response) throws IOException {
|
||||
if (!response.isSuccessful()) {
|
||||
future.setException(new IOException("Response error: " + response));
|
||||
} else {
|
||||
if (response.body() != null) {
|
||||
JsonFormat.parser().ignoringUnknownFields().merge(response.body().string(), responseBuilder);
|
||||
}
|
||||
T protoResponse = (T) responseBuilder.build();
|
||||
future.set(responseConverter.apply(protoResponse));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return future;
|
||||
}
|
||||
|
||||
private <T extends Message> ListenableFuture<T> get(Session session, String path, List<Pair<String, String>> params, T.Builder responseBuilder) {
|
||||
SettableFuture<T> future = SettableFuture.create();
|
||||
HttpUrl.Builder urlBuilder = url.newBuilder().addPathSegments(path);
|
||||
for (Pair<String, String> param : params ) {
|
||||
urlBuilder.addEncodedQueryParameter(param.getFirst(), param.getSecond());
|
||||
}
|
||||
Request request = request(session).newBuilder()
|
||||
.url(urlBuilder.build())
|
||||
.get()
|
||||
.build();
|
||||
|
||||
client.newCall(request).enqueue(new Callback() {
|
||||
@Override
|
||||
public void onFailure(Call call, IOException e) {
|
||||
future.setException(e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResponse(Call call, final Response response) throws IOException {
|
||||
if (!response.isSuccessful()) {
|
||||
future.setException(new IOException("Response error: " + response));
|
||||
} else {
|
||||
if (response.body() != null) {
|
||||
JsonFormat.parser().ignoringUnknownFields().merge(response.body().string(), responseBuilder);
|
||||
}
|
||||
T protoResponse = (T) responseBuilder.build();
|
||||
future.set(protoResponse);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return future;
|
||||
}
|
||||
}
|
||||
@@ -16,9 +16,11 @@
|
||||
|
||||
package com.heroiclabs.satori;
|
||||
|
||||
import com.google.protobuf.Empty;
|
||||
import org.junit.Assert;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@@ -26,21 +28,29 @@ import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.google.common.util.concurrent.ListenableFuture;
|
||||
|
||||
import com.heroiclabs.satori.api.*;
|
||||
|
||||
public class SatoriTest {
|
||||
private Client client;
|
||||
private Client grpcClient, httpClient;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
client = new DefaultClient("bb4b2da1-71ba-429e-b5f3-36556abbf4c9", "127.0.0.1", 7449, false);
|
||||
grpcClient = new DefaultClient("bb4b2da1-71ba-429e-b5f3-36556abbf4c9", "127.0.0.1", 7449, false);
|
||||
httpClient = new HttpClient("bb4b2da1-71ba-429e-b5f3-36556abbf4c9", "127.0.0.1", 7450, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticate() throws Exception {
|
||||
final Session session = client.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
Map<String, String> props = new HashMap<String, String>() {{
|
||||
put("region", "EU");
|
||||
put("language", "en");
|
||||
}};
|
||||
Session session = grpcClient.authenticate(UUID.randomUUID().toString(), props, new HashMap<>()).get();
|
||||
Assert.assertNotNull(session);
|
||||
Assert.assertNotNull(session.getRefreshToken());
|
||||
Assert.assertNotNull(session.getAuthToken());
|
||||
|
||||
session = httpClient.authenticate(UUID.randomUUID().toString(), props, new HashMap<>()).get();
|
||||
Assert.assertNotNull(session);
|
||||
Assert.assertNotNull(session.getRefreshToken());
|
||||
Assert.assertNotNull(session.getAuthToken());
|
||||
@@ -48,22 +58,82 @@ public class SatoriTest {
|
||||
|
||||
@Test
|
||||
public void testLogout() throws Exception {
|
||||
final Session session = client.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
final Session session = grpcClient.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
Assert.assertNotNull(session);
|
||||
client.authenticateLogout(session).get();
|
||||
Assert.assertThrows(Exception.class, () -> client.getFlags(session, new String[]{}).get());
|
||||
grpcClient.authenticateLogout(session).get();
|
||||
Assert.assertThrows(Exception.class, () -> grpcClient.getFlags(session, new String[]{}).get());
|
||||
|
||||
final Session session2 = httpClient.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
Assert.assertNotNull(session2);
|
||||
httpClient.authenticateLogout(session2).get();
|
||||
Assert.assertThrows(Exception.class, () -> httpClient.getFlags(session2, new String[]{}).get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetExperiments() throws Exception {
|
||||
final Session session = client.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
final ExperimentList experimentList = client.getAllExperiments(session).get();
|
||||
Assert.assertTrue(experimentList.getExperimentsCount() == 1);
|
||||
Session session = grpcClient.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
ExperimentList experimentList = grpcClient.getAllExperiments(session).get();
|
||||
Assert.assertEquals(1, experimentList.getExperimentsCount());
|
||||
|
||||
session = httpClient.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
experimentList = httpClient.getAllExperiments(session).get();
|
||||
Assert.assertEquals(1, experimentList.getExperimentsCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFlags() throws Exception {
|
||||
Session session = grpcClient.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
FlagList flagList = grpcClient.getFlags(session).get();
|
||||
Assert.assertEquals(3, flagList.getFlagsCount());
|
||||
|
||||
session = httpClient.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
flagList = httpClient.getFlags(session).get();
|
||||
Assert.assertEquals(3, flagList.getFlagsCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFlag() throws Exception {
|
||||
Session session = grpcClient.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
Flag flag = grpcClient.getFlag(session, "MinBuildNumber").get();
|
||||
Assert.assertNotNull(flag);
|
||||
|
||||
session = httpClient.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
flag = httpClient.getFlag(session, "MinBuildNumber").get();
|
||||
Assert.assertNotNull(flag);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetFlagDefaultValue() throws Exception {
|
||||
|
||||
String bogusAuthToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaWQiOiJmYTk1NDkxMS0xOGQ5LTQyODAtYTQ5ZC0yOGVmODAzNTdlNGUiLCJpaWQiOiIwNTk1MzAxNy00ODY4LTQ2MDQtYjM2Ni1kZWMxZWUyZjIyYWEiLCJleHAiOjE2ODk2OTYzNjQsImlhdCI6MTY4OTY5Mjc2NCwiYXBpIjoiYW5kcm9pZCJ9.J_KohdF3A_huhim8w9OUxVQ18UcCrmeUZeBkwgaSBwU";
|
||||
String bogusRefreshToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaWQiOiJmYTk1NDkxMS0xOGQ5LTQyODAtYTQ5ZC0yOGVmODAzNTdlNGUiLCJpaWQiOiIwNTk1MzAxNy00ODY4LTQ2MDQtYjM2Ni1kZWMxZWUyZjIyYWEiLCJleHAiOjE2ODk2OTYzNjQsImlhdCI6MTY4OTY5Mjc2NH0.6K3WoIg1RsSI1Uwfqn6EPg5Kum7VLwq_eu0Inwl4nMk";
|
||||
|
||||
Client grpcClientNoNetwork = new DefaultClient("bb4b2da1-71ba-429e-b5f3-36556abbf4c9", "0.0.0.0", 7449, false);
|
||||
Flag flag = grpcClientNoNetwork.getFlag(new DefaultSession(bogusAuthToken, bogusRefreshToken), "MinBuildNumber", "true").get();
|
||||
Assert.assertNotNull(flag);
|
||||
Assert.assertEquals("true", flag.getValue());
|
||||
|
||||
Client httpClientNoNetwork = new HttpClient("bb4b2da1-71ba-429e-b5f3-36556abbf4c9", "0.0.0.0", 7450, false);
|
||||
flag = httpClientNoNetwork.getFlag(new DefaultSession(bogusAuthToken, bogusRefreshToken), "MinBuildNumber", "true").get();
|
||||
Assert.assertNotNull(flag);
|
||||
Assert.assertEquals("true", flag.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteIdentity() throws Exception {
|
||||
Session session = grpcClient.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
Empty empty = grpcClient.deleteIdentity(session).get();
|
||||
Assert.assertNotNull(empty);
|
||||
|
||||
session = httpClient.authenticate(UUID.randomUUID().toString(), new HashMap<String, String>(), new HashMap<String, String>()).get();
|
||||
empty = httpClient.deleteIdentity(session).get();
|
||||
Assert.assertNotNull(empty);
|
||||
}
|
||||
|
||||
|
||||
@After
|
||||
public void shutdown() throws Exception {
|
||||
client.disconnect(5000, TimeUnit.MILLISECONDS);
|
||||
grpcClient.disconnect(5000, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user