Skip to content

Commit

Permalink
Applied Fromanator's patch (see pull request cfg4j#145 from original …
Browse files Browse the repository at this point in the history
…repo) and changed artifact id
  • Loading branch information
Maarten Raaphorst committed Aug 24, 2017
1 parent 3a5daef commit 4c5bb61
Show file tree
Hide file tree
Showing 8 changed files with 144 additions and 60 deletions.
50 changes: 25 additions & 25 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ buildscript {

ext {
artifactGroup = "org.cfg4j"
artifactVersion = "4.4.1"
artifactVersion = "4.4.2-SNAPSHOT"
}

repositories {
Expand All @@ -35,7 +35,7 @@ buildscript {

// Generate Gradle wrapper
task wrapper(type: Wrapper) {
gradleVersion = "2.14.1"
gradleVersion = "4.1"
}

subprojects {
Expand Down Expand Up @@ -111,15 +111,15 @@ subprojects {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }

def ossrhUsername = project.findProperty("ossrhUsername") ?: ""
def ossrhPassword = project.findProperty("ossrhPassword") ?: ""
def nexusUsername = project.findProperty("nexusUsername") ?: ""
def nexusPassword = project.findProperty("nexusPassword") ?: ""

repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
authentication(userName: ossrhUsername, password: ossrhPassword)
repository(url: "https://maven.serviceplanet.nl/content/repositories/releases/") {
authentication(userName: nexusUsername, password: nexusPassword)
}

snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
authentication(userName: ossrhUsername, password: ossrhPassword)
snapshotRepository(url: "https://maven.serviceplanet.nl/content/repositories/snapshots/") {
authentication(userName: nexusUsername, password: nexusPassword)
}

pom.project {
Expand All @@ -129,9 +129,9 @@ subprojects {
url 'http://cfg4j.org'

scm {
url 'git@github.com:cfg4j/cfg4j.git'
connection 'scm:git:git@github.com:cfg4j/cfg4j.git'
developerConnection 'scm:git:git@github.com:cfg4j/cfg4j.git'
url 'git@github.com:MaartenR/cfg4j.git'
connection 'scm:git@github.com:MaartenR/cfg4j.git'
developerConnection 'scm:git@github.com:MaartenR/cfg4j.git'
}


Expand Down Expand Up @@ -161,19 +161,19 @@ subprojects {
sign configurations.archives
}

gradle.taskGraph.whenReady { taskGraph ->
if (taskGraph.hasTask(":cfg4j-core:uploadArchives")) {
Console console = System.console()
console.printf "\n\nWe have to sign and upload artifacts to Maven Central Repository" +
"\n\nPlease enter your credentials.\n\n"

def signingPassword = console.readPassword("PGP Private Key Password: ")

allprojects { ext."signing.password" = signingPassword }


console.printf "\nThanks.\n\n"
}
}
// gradle.taskGraph.whenReady { taskGraph ->
// if (taskGraph.hasTask(":cfg4j-core:uploadArchives")) {
// Console console = System.console()
// console.printf "\n\nWe have to sign and upload artifacts to Maven Central Repository" +
// "\n\nPlease enter your credentials.\n\n"
//
// def signingPassword = console.readPassword("PGP Private Key Password: ")
//
// allprojects { ext."signing.password" = signingPassword }
//
//
// console.printf "\nThanks.\n\n"
// }
// }

}
2 changes: 1 addition & 1 deletion cfg4j-consul/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
buildscript {

ext {
artifactName = "cfg4j-consul"
artifactName = "cfg4j-consul-spfork"
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,16 @@

/**
* Note: use {@link ConsulConfigurationSourceBuilder} for building instances of this class.
*
* <p>
* This source interpretes the provided {@link Environment} variable as a Consul Key Prefix.
* If you build this Source without passing the {@link Environment} to {@link ConsulConfigurationSourceBuilder#withEnvironment(Environment)}
* then by default all values will be fetched from Consul to be matched.
* </p>
*
* <p>
* Read configuration from the Consul K-V store.
* </p>
*/
public class ConsulConfigurationSource implements ConfigurationSource {

Expand All @@ -46,6 +54,7 @@ public class ConsulConfigurationSource implements ConfigurationSource {
private final String host;
private final int port;
private boolean initialized;
private final Environment environment;

/**
* Note: use {@link ConsulConfigurationSourceBuilder} for building instances of this class.
Expand All @@ -55,9 +64,10 @@ public class ConsulConfigurationSource implements ConfigurationSource {
* @param host Consul host to connect to
* @param port Consul port to connect to
*/
ConsulConfigurationSource(String host, int port) {
ConsulConfigurationSource(String host, int port, Environment environment) {
this.host = requireNonNull(host);
this.port = port;
this.environment = environment;

initialized = false;
}
Expand All @@ -73,19 +83,11 @@ public Properties getConfiguration(Environment environment) {
reload();

Properties properties = new Properties();
String path = environment.getName();

if (path.startsWith("/")) {
path = path.substring(1);
}

if (path.length() > 0 && !path.endsWith("/")) {
path = path + "/";
}
String environmentPrefix = formatEnvironment(environment);

for (Map.Entry<String, String> entry : consulValues.entrySet()) {
if (entry.getKey().startsWith(path)) {
properties.put(entry.getKey().substring(path.length()).replace("/", "."), entry.getValue());
if (entry.getKey().startsWith(environmentPrefix)) {
properties.put(entry.getKey().substring(environmentPrefix.length()).replace("/", "."), entry.getValue());
}
}

Expand Down Expand Up @@ -115,8 +117,9 @@ private void reload() {
List<Value> valueList;

try {
LOG.debug("Reloading configuration from Consuls' K-V store");
valueList = kvClient.getValues("/");
String consulKeyPath = formatEnvironmentToConsulKeyPrefix(environment);
LOG.debug("Reloading configuration from Consuls' K-V store for Prefix: " + consulKeyPath);
valueList = kvClient.getValues(consulKeyPath);
} catch (Exception e) {
throw new SourceCommunicationException("Can't get values from k-v store", e);
}
Expand All @@ -143,4 +146,31 @@ public String toString() {
", kvClient=" + kvClient +
'}';
}

private static String formatEnvironmentToConsulKeyPrefix(Environment environment) {
String path = environment.getName();

if (path.startsWith("/")) {
path = path.substring(1);
}

if(path.length() > 0 && path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
return path.isEmpty() ? "/" : path;
}

private static String formatEnvironment(Environment environment) {
String path = environment.getName();

if (path.startsWith("/")) {
path = path.substring(1);
}

if (path.length() > 0 && !path.endsWith("/")) {
path = path + "/";
}

return path;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,17 @@
*/
package org.cfg4j.source.consul;

import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;

/**
* Builder for {@link ConsulConfigurationSource}.
*/
public class ConsulConfigurationSourceBuilder {

private String host;
private int port;
private Environment environment;

/**
* Construct {@link ConsulConfigurationSource}s builder
Expand All @@ -35,6 +39,7 @@ public class ConsulConfigurationSourceBuilder {
public ConsulConfigurationSourceBuilder() {
host = "localhost";
port = 8500;
environment = new ImmutableEnvironment("/");
}

/**
Expand All @@ -59,20 +64,32 @@ public ConsulConfigurationSourceBuilder withPort(int port) {
return this;
}

/**
* Set the {@link Environment} to use as your Consul Key Prefix root for configuration.
*
* @param environment a {@link Environment} interpreted as a Consul Key Prefix
* @return this builder with the Environment set to the provided Environment
*/
public ConsulConfigurationSourceBuilder withEnvironment(Environment environment) {
this.environment = environment;
return this;
}

/**
* Build a {@link ConsulConfigurationSource} using this builder's configuration
*
* @return new {@link ConsulConfigurationSource}
*/
public ConsulConfigurationSource build() {
return new ConsulConfigurationSource(host, port);
return new ConsulConfigurationSource(host, port,environment);
}

@Override
public String toString() {
return "ConsulConfigurationSource{" +
"host=" + host +
", port=" + port +
", environment=" + environment +
'}';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.internal.exceptions.ExceptionIncludingMockitoWarnings;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.IOException;
Expand All @@ -48,28 +49,45 @@ private class ModifiableDispatcher extends Dispatcher {
private static final String disabledBase64 = "ZGlzYWJsZWQ=";
private static final String enabledBase64 = "ZW5hYmxlZA==";

private static final String usWest1Config = "{\"CreateIndex\":1,\"ModifyIndex\":1,\"LockIndex\":0,\"Key\":\"us-west-1/featureA.toggle\",\"Flags\":0,\"Value\":\"" + disabledBase64 + "\"}";
private static final String usWest2FeatureEnable = "{\"CreateIndex\":2,\"ModifyIndex\":2,\"LockIndex\":0,\"Key\":\"us-west-2/featureB.toggle\",\"Flags\":0,\"Value\":\"" + enabledBase64 + "\"}";
private static final String usWest2FeatureDisabled = "{\"CreateIndex\":2,\"ModifyIndex\":2,\"LockIndex\":0,\"Key\":\"us-west-2/featureB.toggle\",\"Flags\":0,\"Value\":\"" + disabledBase64 + "\"}";

private boolean usWest2Toggle = false;

void toggleUsWest2() {
usWest2Toggle = !usWest2Toggle;
}

@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {

switch (request.getPath()) {
case "/v1/agent/self":
return new MockResponse().setResponseCode(200).setBody(PING_RESPONSE);
case "/v1/kv/?recurse=true":
return new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json; charset=utf-8")
.setBody("[{\"CreateIndex\":1,\"ModifyIndex\":1,\"LockIndex\":0,\"Key\":\"us-west-1/featureA.toggle\",\"Flags\":0,\"Value\":\"ZGlzYWJsZWQ=\"},"
+ "{\"CreateIndex\":2,\"ModifyIndex\":2,\"LockIndex\":0,\"Key\":\"us-west-2/featureA.toggle\",\"Flags\":0,\"Value\":\""
+ (usWest2Toggle ? enabledBase64 : disabledBase64) + "\"}]");
}
return new MockResponse().setResponseCode(404);
}
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
StringBuilder sbResponseBody = new StringBuilder();
switch (request.getPath()) {
case "/v1/agent/self":
return new MockResponse().setResponseCode(200).setBody(PING_RESPONSE);
case "/v1/kv/?recurse=true":
sbResponseBody.append("[");
sbResponseBody.append(usWest1Config).append(",");
if(usWest2Toggle) {
sbResponseBody.append(usWest2FeatureEnable);
} else {
sbResponseBody.append(usWest2FeatureDisabled);
}
sbResponseBody.append("]");

return new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json; charset=utf-8")
.setBody(sbResponseBody.toString());

case "/v1/kv/us-west-1?recurse=true":
return new MockResponse()
.setResponseCode(200)
.addHeader("Content-Type", "application/json; charset=utf-8")
.setBody("[" + usWest1Config + "]");
}
return new MockResponse().setResponseCode(404);
}
}

@Rule
Expand Down Expand Up @@ -152,6 +170,25 @@ public void getConfigurationThrowsAfterFailedReload() throws Exception {
source.getConfiguration(new ImmutableEnvironment(""));
}

@Test
public void getConfigurationWithSourceEnvironmentSetShouldReturnOnlyKeysInEnvironment() throws Exception {
Environment environment = new ImmutableEnvironment("/us-west-1");
Environment noEnvironment = new ImmutableEnvironment("");

ConsulConfigurationSource source = new ConsulConfigurationSourceBuilder()
.withHost(server.getHostName())
.withPort(server.getPort())
.withEnvironment(environment)
.build();

source.init();

// Match with any prefix, we shouldn't have gotten us-west-2 data back
assertThat(source.getConfiguration(noEnvironment)).doesNotContain(MapEntry.entry("featureB.toggle", "disabled"));

assertThat(source.getConfiguration(environment)).contains(MapEntry.entry("featureA.toggle", "disabled"));
}

private void runMockServer() throws IOException {
server = new MockWebServer();
server.setDispatcher(dispatcher);
Expand Down
2 changes: 1 addition & 1 deletion cfg4j-core/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
buildscript {

ext {
artifactName = "cfg4j-core"
artifactName = "cfg4j-core-spfork"
}
}

Expand Down
2 changes: 1 addition & 1 deletion cfg4j-git/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
buildscript {

ext {
artifactName = "cfg4j-git"
artifactName = "cfg4j-git-spfork"
}
}

Expand Down
2 changes: 1 addition & 1 deletion cfg4j-s3/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
buildscript {

ext {
artifactName = "cfg4j-s3"
artifactName = "cfg4j-s3-spfork"
}

repositories {
Expand Down

0 comments on commit 4c5bb61

Please sign in to comment.