| 1 |
/* |
| 2 |
* Licensed to the Apache Software Foundation (ASF) under one |
| 3 |
* or more contributor license agreements. See the NOTICE file |
| 4 |
* distributed with this work for additional information |
| 5 |
* regarding copyright ownership. The ASF licenses this file |
| 6 |
* to you under the Apache License, Version 2.0 (the |
| 7 |
* "License"); you may not use this file except in compliance |
| 8 |
* with the License. You may obtain a copy of the License at |
| 9 |
* |
| 10 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 11 |
* |
| 12 |
* Unless required by applicable law or agreed to in writing, |
| 13 |
* software distributed under the License is distributed on an |
| 14 |
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 |
* KIND, either express or implied. See the License for the |
| 16 |
* specific language governing permissions and limitations |
| 17 |
* under the License. |
| 18 |
*/ |
| 19 |
|
| 20 |
package pubsub; |
| 21 |
|
| 22 |
import java.io.Closeable; |
| 23 |
import java.io.IOException; |
| 24 |
import java.time.Duration; |
| 25 |
import java.util.ArrayList; |
| 26 |
import java.util.Arrays; |
| 27 |
import java.util.List; |
| 28 |
import java.util.concurrent.Executors; |
| 29 |
import java.util.concurrent.ScheduledExecutorService; |
| 30 |
import java.util.concurrent.ThreadLocalRandom; |
| 31 |
import java.util.concurrent.TimeUnit; |
| 32 |
import java.util.concurrent.atomic.AtomicLong; |
| 33 |
import java.util.stream.Collectors; |
| 34 |
import java.util.stream.IntStream; |
| 35 |
import org.apache.curator.framework.CuratorFrameworkFactory; |
| 36 |
import org.apache.curator.retry.RetryOneTime; |
| 37 |
import org.apache.curator.test.TestingServer; |
| 38 |
import org.apache.curator.x.async.AsyncCuratorFramework; |
| 39 |
import org.apache.curator.x.async.modeled.cached.CachedModeledFramework; |
| 40 |
import org.apache.curator.x.async.modeled.cached.ModeledCacheListener; |
| 41 |
import pubsub.messages.LocationAvailable; |
| 42 |
import pubsub.messages.UserCreated; |
| 43 |
import pubsub.models.Group; |
| 44 |
import pubsub.models.Instance; |
| 45 |
import pubsub.models.InstanceType; |
| 46 |
import pubsub.models.Priority; |
| 47 |
|
| 48 |
public class SubPubTest implements Closeable { |
| 49 |
private final TestingServer testingServer; |
| 50 |
private final AsyncCuratorFramework client; |
| 51 |
private final ScheduledExecutorService executorService; |
| 52 |
private final List<CachedModeledFramework<Instance>> instanceSubscribers = new ArrayList<>(); |
| 53 |
private final List<CachedModeledFramework<LocationAvailable>> locationAvailableSubscribers = new ArrayList<>(); |
| 54 |
private final List<CachedModeledFramework<UserCreated>> userCreatedSubscribers = new ArrayList<>(); |
| 55 |
|
| 56 |
private static final AtomicLong nextId = new AtomicLong(1); |
| 57 |
|
| 58 |
// arrays of random values used for this example |
| 59 |
private static final Group[] groups = {new Group("main"), new Group("admin")}; |
| 60 |
private static final String[] hostnames = {"host1", "host2", "host3"}; |
| 61 |
private static final Integer[] ports = {80, 443, 9999}; |
| 62 |
private static final String[] locations = {"dc1", "dc2", "eu", "us"}; |
| 63 |
private static final Duration[] durations = {Duration.ofSeconds(1), Duration.ofMinutes(1), Duration.ofHours(1)}; |
| 64 |
private static final String[] positions = {"worker", "manager", "executive"}; |
| 65 |
|
| 66 |
public static void main(String[] args) { |
| 67 |
try (SubPubTest subPubTest = new SubPubTest()) { |
| 68 |
subPubTest.start(); |
| 69 |
TimeUnit.MINUTES.sleep(1); // run the test for a minute then exit |
| 70 |
} catch (Exception e) { |
| 71 |
e.printStackTrace(); |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
public SubPubTest() throws Exception { |
| 76 |
this.testingServer = new TestingServer(); |
| 77 |
client = AsyncCuratorFramework.wrap( |
| 78 |
CuratorFrameworkFactory.newClient(testingServer.getConnectString(), new RetryOneTime(1))); |
| 79 |
executorService = Executors.newSingleThreadScheduledExecutor(); |
| 80 |
} |
| 81 |
|
| 82 |
public void start() { |
| 83 |
client.unwrap().start(); |
| 84 |
|
| 85 |
Publisher publisher = new Publisher(client); |
| 86 |
Subscriber subscriber = new Subscriber(client); |
| 87 |
|
| 88 |
// start a subscriber/cache for Instances of each InstanceType |
| 89 |
instanceSubscribers.addAll(Arrays.stream(InstanceType.values()) |
| 90 |
.map(subscriber::startInstanceSubscriber) |
| 91 |
.collect(Collectors.toList())); |
| 92 |
|
| 93 |
// start a subscriber/cache for LocationAvailables of each combination of Group and Priority |
| 94 |
locationAvailableSubscribers.addAll(Arrays.stream(Priority.values()) |
| 95 |
.flatMap(priority -> Arrays.stream(groups) |
| 96 |
.map(group -> subscriber.startLocationAvailableSubscriber(group, priority))) |
| 97 |
.collect(Collectors.toList())); |
| 98 |
|
| 99 |
// start a subscriber/cache for UserCreateds of each combination of Group and Priority |
| 100 |
userCreatedSubscribers.addAll(Arrays.stream(Priority.values()) |
| 101 |
.flatMap(priority -> |
| 102 |
Arrays.stream(groups).map(group -> subscriber.startUserCreatedSubscriber(group, priority))) |
| 103 |
.collect(Collectors.toList())); |
| 104 |
|
| 105 |
// add listeners for each of the caches |
| 106 |
instanceSubscribers.forEach(s -> s.listenable().addListener(generalListener())); |
| 107 |
locationAvailableSubscribers.forEach(s -> s.listenable().addListener(generalListener())); |
| 108 |
userCreatedSubscribers.forEach(s -> s.listenable().addListener(generalListener())); |
| 109 |
|
| 110 |
// schedule the publisher task once a second |
| 111 |
executorService.scheduleAtFixedRate(() -> publishSomething(publisher), 1, 1, TimeUnit.SECONDS); |
| 112 |
} |
| 113 |
|
| 114 |
@Override |
| 115 |
public void close() throws IOException { |
| 116 |
executorService.shutdownNow(); |
| 117 |
try { |
| 118 |
executorService.awaitTermination(5, TimeUnit.SECONDS); |
| 119 |
} catch (InterruptedException ignore) { |
| 120 |
Thread.currentThread().interrupt(); |
| 121 |
} |
| 122 |
|
| 123 |
userCreatedSubscribers.forEach(CachedModeledFramework::close); |
| 124 |
locationAvailableSubscribers.forEach(CachedModeledFramework::close); |
| 125 |
instanceSubscribers.forEach(CachedModeledFramework::close); |
| 126 |
client.unwrap().close(); |
| 127 |
testingServer.close(); |
| 128 |
} |
| 129 |
|
| 130 |
private void publishSomething(Publisher publisher) { |
| 131 |
// randomly do some publishing - either single items or lists of items in a transaction |
| 132 |
switch (ThreadLocalRandom.current().nextInt(6)) { |
| 133 |
case 0: { |
| 134 |
Instance instance = |
| 135 |
new Instance(nextId(), random(InstanceType.values()), random(hostnames), random(ports)); |
| 136 |
System.out.println("Publishing 1 instance"); |
| 137 |
publisher.publishInstance(instance); |
| 138 |
break; |
| 139 |
} |
| 140 |
|
| 141 |
case 1: { |
| 142 |
List<Instance> instances = IntStream.range(1, 10) |
| 143 |
.mapToObj(__ -> |
| 144 |
new Instance(nextId(), random(InstanceType.values()), random(hostnames), random(ports))) |
| 145 |
.collect(Collectors.toList()); |
| 146 |
System.out.println(String.format("Publishing %d instances", instances.size())); |
| 147 |
publisher.publishInstances(instances); |
| 148 |
break; |
| 149 |
} |
| 150 |
|
| 151 |
case 2: { |
| 152 |
LocationAvailable locationAvailable = new LocationAvailable( |
| 153 |
nextId(), random(Priority.values()), random(locations), random(durations)); |
| 154 |
System.out.println("Publishing 1 locationAvailable"); |
| 155 |
publisher.publishLocationAvailable(random(groups), locationAvailable); |
| 156 |
break; |
| 157 |
} |
| 158 |
|
| 159 |
case 3: { |
| 160 |
List<LocationAvailable> locationsAvailable = IntStream.range(1, 10) |
| 161 |
.mapToObj(__ -> new LocationAvailable( |
| 162 |
nextId(), random(Priority.values()), random(locations), random(durations))) |
| 163 |
.collect(Collectors.toList()); |
| 164 |
System.out.println(String.format("Publishing %d locationsAvailable", locationsAvailable.size())); |
| 165 |
publisher.publishLocationsAvailable(random(groups), locationsAvailable); |
| 166 |
break; |
| 167 |
} |
| 168 |
|
| 169 |
case 4: { |
| 170 |
UserCreated userCreated = |
| 171 |
new UserCreated(nextId(), random(Priority.values()), random(locations), random(positions)); |
| 172 |
System.out.println("Publishing 1 userCreated"); |
| 173 |
publisher.publishUserCreated(random(groups), userCreated); |
| 174 |
break; |
| 175 |
} |
| 176 |
|
| 177 |
case 5: { |
| 178 |
List<UserCreated> usersCreated = IntStream.range(1, 10) |
| 179 |
.mapToObj(__ -> new UserCreated( |
| 180 |
nextId(), random(Priority.values()), random(locations), random(positions))) |
| 181 |
.collect(Collectors.toList()); |
| 182 |
System.out.println(String.format("Publishing %d usersCreated", usersCreated.size())); |
| 183 |
publisher.publishUsersCreated(random(groups), usersCreated); |
| 184 |
break; |
| 185 |
} |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
private <T> ModeledCacheListener<T> generalListener() { |
| 190 |
return (type, path, stat, model) -> System.out.println( |
| 191 |
String.format("Subscribed %s @ %s", model.getClass().getSimpleName(), path)); |
| 192 |
} |
| 193 |
|
| 194 |
@SafeVarargs |
| 195 |
private final <T> T random(T... tab) { |
| 196 |
int index = ThreadLocalRandom.current().nextInt(tab.length); |
| 197 |
return tab[index]; |
| 198 |
} |
| 199 |
|
| 200 |
private String nextId() { |
| 201 |
return Long.toString(nextId.getAndIncrement()); |
| 202 |
} |
| 203 |
} |