Skip to content

Commit b9561fb

Browse files
authored
chore: fixup logging and other style issues (#1255)
Signed-off-by: tison <wander4096@gmail.com>
1 parent 093cbcf commit b9561fb

17 files changed

Lines changed: 95 additions & 142 deletions

File tree

curator-client/src/main/java/org/apache/curator/CuratorZookeeperClient.java

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
import org.apache.curator.utils.DefaultZookeeperFactory;
3535
import org.apache.curator.utils.ThreadUtils;
3636
import org.apache.curator.utils.ZookeeperFactory;
37-
import org.apache.zookeeper.WatchedEvent;
3837
import org.apache.zookeeper.Watcher;
3938
import org.apache.zookeeper.ZooKeeper;
4039
import org.slf4j.Logger;
@@ -47,11 +46,11 @@
4746
public class CuratorZookeeperClient implements Closeable {
4847
private final Logger log = LoggerFactory.getLogger(getClass());
4948
private final ConnectionState state;
50-
private final AtomicReference<RetryPolicy> retryPolicy = new AtomicReference<RetryPolicy>();
49+
private final AtomicReference<RetryPolicy> retryPolicy = new AtomicReference<>();
5150
private final int connectionTimeoutMs;
5251
private final int waitForShutdownTimeoutMs;
5352
private final AtomicBoolean started = new AtomicBoolean(false);
54-
private final AtomicReference<TracerDriver> tracer = new AtomicReference<TracerDriver>(new DefaultTracerDriver());
53+
private final AtomicReference<TracerDriver> tracer = new AtomicReference<>(new DefaultTracerDriver());
5554

5655
/**
5756
*
@@ -155,13 +154,12 @@ public CuratorZookeeperClient(
155154
RetryPolicy retryPolicy,
156155
boolean canBeReadOnly) {
157156
if (sessionTimeoutMs < connectionTimeoutMs) {
158-
log.warn(String.format(
159-
"session timeout [%d] is less than connection timeout [%d]",
160-
sessionTimeoutMs, connectionTimeoutMs));
157+
log.warn(
158+
"session timeout [{}] is less than connection timeout [{}]", sessionTimeoutMs, connectionTimeoutMs);
161159
}
162160

163-
retryPolicy = Preconditions.checkNotNull(retryPolicy, "retryPolicy cannot be null");
164-
ensembleProvider = Preconditions.checkNotNull(ensembleProvider, "ensembleProvider cannot be null");
161+
Preconditions.checkNotNull(retryPolicy, "retryPolicy cannot be null");
162+
Preconditions.checkNotNull(ensembleProvider, "ensembleProvider cannot be null");
165163

166164
this.connectionTimeoutMs = connectionTimeoutMs;
167165
this.waitForShutdownTimeoutMs = waitForShutdownTimeoutMs;
@@ -213,7 +211,7 @@ public boolean isConnected() {
213211

214212
/**
215213
* This method blocks until the connection to ZK succeeds. Use with caution. The block
216-
* will timeout after the connection timeout (as passed to the constructor) has elapsed
214+
* will time out after the connection timeout (as passed to the constructor) has elapsed
217215
*
218216
* @return true if the connection succeeded, false if not
219217
* @throws InterruptedException interrupted while waiting
@@ -229,7 +227,7 @@ public boolean blockUntilConnectedOrTimedOut() throws InterruptedException {
229227
trace.commit();
230228

231229
boolean localIsConnected = state.isConnected();
232-
log.debug("blockUntilConnectedOrTimedOut() end. isConnected: " + localIsConnected);
230+
log.debug("blockUntilConnectedOrTimedOut() end. isConnected: {}", localIsConnected);
233231

234232
return localIsConnected;
235233
}
@@ -252,7 +250,7 @@ public void start() throws Exception {
252250
/**
253251
* Close the client.
254252
*
255-
* Same as {@link #close(int) } using the timeout set at construction time.
253+
* <p>Same as {@link #close(int) } using the timeout set at construction time.</p>
256254
*
257255
* @see #close(int)
258256
*/
@@ -403,12 +401,7 @@ public void internalBlockUntilConnectedOrTimedOut() throws InterruptedException
403401
throw new IllegalStateException("Client is not started or has been closed");
404402
}
405403
final CountDownLatch latch = new CountDownLatch(1);
406-
Watcher tempWatcher = new Watcher() {
407-
@Override
408-
public void process(WatchedEvent event) {
409-
latch.countDown();
410-
}
411-
};
404+
final Watcher tempWatcher = event -> latch.countDown();
412405

413406
state.addParentWatcher(tempWatcher);
414407
long startTimeMs = System.currentTimeMillis();

curator-client/src/main/java/org/apache/curator/retry/ExponentialBackoffRetry.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,15 +66,15 @@ protected long getSleepTimeMs(int retryCount, long elapsedTimeMs) {
6666
// copied from Hadoop's RetryPolicies.java
6767
long sleepMs = (long) baseSleepTimeMs * Math.max(1, random.nextInt(1 << (retryCount + 1)));
6868
if (sleepMs > maxSleepMs) {
69-
log.warn(String.format("Sleep extension too large (%d). Pinning to %d", sleepMs, maxSleepMs));
69+
log.warn("Sleep extension too large ({}). Pinning to {}", sleepMs, maxSleepMs);
7070
sleepMs = maxSleepMs;
7171
}
7272
return sleepMs;
7373
}
7474

7575
private static int validateMaxRetries(int maxRetries) {
7676
if (maxRetries > MAX_RETRIES_LIMIT) {
77-
log.warn(String.format("maxRetries too large (%d). Pinning to %d", maxRetries, MAX_RETRIES_LIMIT));
77+
log.warn("maxRetries too large ({}). Pinning to {}", maxRetries, MAX_RETRIES_LIMIT);
7878
maxRetries = MAX_RETRIES_LIMIT;
7979
}
8080
return maxRetries;

curator-examples/src/main/java/cache/CuratorCacheExample.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,10 @@ public static void main(String[] args) throws Exception {
4444
// there are several ways to set a listener on a CuratorCache. You can watch for individual events
4545
// or for all events. Here, we'll use the builder to log individual cache actions
4646
CuratorCacheListener listener = CuratorCacheListener.builder()
47-
.forCreates(node -> System.out.println(String.format("Node created: [%s]", node)))
48-
.forChanges((oldNode, node) -> System.out.println(
49-
String.format("Node changed. Old: [%s] New: [%s]", oldNode, node)))
50-
.forDeletes(oldNode ->
51-
System.out.println(String.format("Node deleted. Old value: [%s]", oldNode)))
47+
.forCreates(node -> System.out.printf("Node created: [%s]%n", node))
48+
.forChanges((oldNode, node) ->
49+
System.out.printf("Node changed. Old: [%s] New: [%s]%n", oldNode, node))
50+
.forDeletes(oldNode -> System.out.printf("Node deleted. Old value: [%s]%n", oldNode))
5251
.forInitialized(() -> System.out.println("Cache initialized"))
5352
.build();
5453

curator-examples/src/main/java/pubsub/SubPubTest.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ private void publishSomething(Publisher publisher) {
143143
.mapToObj(__ ->
144144
new Instance(nextId(), random(InstanceType.values()), random(hostnames), random(ports)))
145145
.collect(Collectors.toList());
146-
System.out.println(String.format("Publishing %d instances", instances.size()));
146+
System.out.printf("Publishing %d instances%n", instances.size());
147147
publisher.publishInstances(instances);
148148
break;
149149
}
@@ -161,7 +161,7 @@ private void publishSomething(Publisher publisher) {
161161
.mapToObj(__ -> new LocationAvailable(
162162
nextId(), random(Priority.values()), random(locations), random(durations)))
163163
.collect(Collectors.toList());
164-
System.out.println(String.format("Publishing %d locationsAvailable", locationsAvailable.size()));
164+
System.out.printf("Publishing %d locationsAvailable%n", locationsAvailable.size());
165165
publisher.publishLocationsAvailable(random(groups), locationsAvailable);
166166
break;
167167
}
@@ -179,16 +179,16 @@ private void publishSomething(Publisher publisher) {
179179
.mapToObj(__ -> new UserCreated(
180180
nextId(), random(Priority.values()), random(locations), random(positions)))
181181
.collect(Collectors.toList());
182-
System.out.println(String.format("Publishing %d usersCreated", usersCreated.size()));
182+
System.out.printf("Publishing %d usersCreated%n", usersCreated.size());
183183
publisher.publishUsersCreated(random(groups), usersCreated);
184184
break;
185185
}
186186
}
187187
}
188188

189189
private <T> ModeledCacheListener<T> generalListener() {
190-
return (type, path, stat, model) -> System.out.println(
191-
String.format("Subscribed %s @ %s", model.getClass().getSimpleName(), path));
190+
return (type, path, stat, model) ->
191+
System.out.printf("Subscribed %s @ %s%n", model.getClass().getSimpleName(), path);
192192
}
193193

194194
@SafeVarargs

curator-framework/src/main/java/org/apache/curator/framework/imps/CuratorFrameworkBase.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ final ZooKeeper getZooKeeper() throws Exception {
113113

114114
protected final void internalSync(CuratorFrameworkBase impl, String path, Object context) {
115115
BackgroundOperation<String> operation = new BackgroundSyncImpl(impl, context);
116-
processBackgroundOperation(new OperationAndData(operation, path, null, null, context, null), null);
116+
processBackgroundOperation(new OperationAndData<>(operation, path, null, null, context, null), null);
117117
}
118118

119119
abstract byte[] getDefaultData();

curator-framework/src/main/java/org/apache/curator/framework/listen/MappingListenerManager.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ public void forEach(Consumer<V> function) {
8282
function.accept(entry.listener);
8383
} catch (Throwable e) {
8484
ThreadUtils.checkInterrupted(e);
85-
log.error(String.format("Listener (%s) threw an exception", entry.listener), e);
85+
log.error("Listener ({}) threw an exception", entry.listener, e);
8686
}
8787
});
8888
}

curator-framework/src/main/java/org/apache/curator/framework/state/ConnectionStateManager.java

Lines changed: 19 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import java.io.Closeable;
2424
import java.util.concurrent.ArrayBlockingQueue;
2525
import java.util.concurrent.BlockingQueue;
26-
import java.util.concurrent.Callable;
2726
import java.util.concurrent.ExecutorService;
2827
import java.util.concurrent.Executors;
2928
import java.util.concurrent.ThreadFactory;
@@ -57,13 +56,13 @@ public class ConnectionStateManager implements Closeable {
5756
}
5857

5958
private final Logger log = LoggerFactory.getLogger(getClass());
60-
private final BlockingQueue<ConnectionState> eventQueue = new ArrayBlockingQueue<ConnectionState>(QUEUE_SIZE);
59+
private final BlockingQueue<ConnectionState> eventQueue = new ArrayBlockingQueue<>(QUEUE_SIZE);
6160
private final CuratorFramework client;
6261
private final int sessionTimeoutMs;
6362
private final int sessionExpirationPercent;
6463
private final AtomicBoolean initialConnectMessageSent = new AtomicBoolean(false);
6564
private final ExecutorService service;
66-
private final AtomicReference<State> state = new AtomicReference<State>(State.LATENT);
65+
private final AtomicReference<State> state = new AtomicReference<>(State.LATENT);
6766
private final UnaryListenerManager<ConnectionStateListener> listeners;
6867

6968
// guarded by sync
@@ -80,9 +79,9 @@ private enum State {
8079
}
8180

8281
/**
83-
* @param client the client
84-
* @param threadFactory thread factory to use or null for a default
85-
* @param sessionTimeoutMs the ZK session timeout in milliseconds
82+
* @param client the client
83+
* @param threadFactory thread factory to use or null for a default
84+
* @param sessionTimeoutMs the ZK session timeout in milliseconds
8685
* @param sessionExpirationPercent percentage of negotiated session timeout to use when simulating a session timeout. 0 means don't simulate at all
8786
*/
8887
public ConnectionStateManager(
@@ -96,11 +95,11 @@ public ConnectionStateManager(
9695
}
9796

9897
/**
99-
* @param client the client
100-
* @param threadFactory thread factory to use or null for a default
101-
* @param sessionTimeoutMs the ZK session timeout in milliseconds
98+
* @param client the client
99+
* @param threadFactory thread factory to use or null for a default
100+
* @param sessionTimeoutMs the ZK session timeout in milliseconds
102101
* @param sessionExpirationPercent percentage of negotiated session timeout to use when simulating a session timeout. 0 means don't simulate at all
103-
* @param managerFactory manager factory to use
102+
* @param managerFactory manager factory to use
104103
*/
105104
public ConnectionStateManager(
106105
CuratorFramework client,
@@ -124,12 +123,9 @@ public ConnectionStateManager(
124123
public void start() {
125124
Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "Cannot be started more than once");
126125

127-
service.submit(new Callable<Object>() {
128-
@Override
129-
public Object call() throws Exception {
130-
processEvents();
131-
return null;
132-
}
126+
service.submit(() -> {
127+
processEvents();
128+
return null;
133129
});
134130
}
135131

@@ -173,7 +169,7 @@ public synchronized boolean setToSuspended() {
173169

174170
/**
175171
* Post a state change. If the manager is already in that state the change
176-
* is ignored. Otherwise the change is queued for listeners.
172+
* is ignored. Otherwise, the change is queued for listeners.
177173
*
178174
* @param newConnectionState new state
179175
* @return true if the state actually changed, false if it was already at that state
@@ -228,7 +224,7 @@ public synchronized boolean isConnected() {
228224
}
229225

230226
private void postState(ConnectionState state) {
231-
log.info("State change: " + state);
227+
log.info("State change: {}", state);
232228

233229
notifyAll();
234230

@@ -265,7 +261,7 @@ private void processEvents() {
265261
&& client.getZookeeperClient().isConnected()) {
266262
// CURATOR-525 - there is a race whereby LOST is sometimes set after the connection has been
267263
// repaired
268-
// this "hack" fixes it by forcing the state to RECONNECTED
264+
// this "hack" fixes it by forcing the state to "RECONNECTED"
269265
log.warn("ConnectionState is LOST but isConnected() is true. Forcing RECONNECTED.");
270266
addStateChange(ConnectionState.RECONNECTED);
271267
}
@@ -286,9 +282,10 @@ private void checkSessionExpiration() {
286282
startOfSuspendedEpoch =
287283
System.currentTimeMillis(); // reset startOfSuspendedEpoch to avoid spinning on this session
288284
// expiration injection CURATOR-405
289-
log.warn(String.format(
290-
"Session timeout has elapsed while SUSPENDED. Injecting a session expiration. Elapsed ms: %d. Adjusted session timeout ms: %d",
291-
elapsedMs, useSessionTimeoutMs));
285+
log.warn(
286+
"Session timeout has elapsed while SUSPENDED. Injecting a session expiration. Elapsed ms: {}. Adjusted session timeout ms: {}",
287+
elapsedMs,
288+
useSessionTimeoutMs);
292289
try {
293290
if (lastExpiredInstanceIndex == client.getZookeeperClient().getInstanceIndex()) {
294291
// last expiration didn't work for this instance, so event thread is dead and a reset is needed.

curator-recipes/src/main/java/org/apache/curator/framework/recipes/atomic/DistributedAtomicValue.java

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ public DistributedAtomicValue(
8181
* @throws Exception ZooKeeper errors
8282
*/
8383
public AtomicValue<byte[]> get() throws Exception {
84-
MutableAtomicValue<byte[]> result = new MutableAtomicValue<byte[]>(null, null, false);
84+
MutableAtomicValue<byte[]> result = new MutableAtomicValue<>(null, null, false);
8585
getCurrentValue(result, new Stat());
8686
result.postValue = result.preValue;
8787
result.succeeded = true;
@@ -119,16 +119,14 @@ public void forceSet(byte[] newValue) throws Exception {
119119
*/
120120
public AtomicValue<byte[]> compareAndSet(byte[] expectedValue, byte[] newValue) throws Exception {
121121
Stat stat = new Stat();
122-
MutableAtomicValue<byte[]> result = new MutableAtomicValue<byte[]>(null, null, false);
122+
MutableAtomicValue<byte[]> result = new MutableAtomicValue<>(null, null, false);
123123
boolean createIt = getCurrentValue(result, stat);
124124
if (!createIt && Arrays.equals(expectedValue, result.preValue)) {
125125
try {
126126
client.setData().withVersion(stat.getVersion()).forPath(path, newValue);
127127
result.succeeded = true;
128128
result.postValue = newValue;
129-
} catch (KeeperException.BadVersionException dummy) {
130-
result.succeeded = false;
131-
} catch (KeeperException.NoNodeException dummy) {
129+
} catch (KeeperException.BadVersionException | KeeperException.NoNodeException dummy) {
132130
result.succeeded = false;
133131
}
134132
} else {
@@ -146,14 +144,9 @@ public AtomicValue<byte[]> compareAndSet(byte[] expectedValue, byte[] newValue)
146144
* @throws Exception ZooKeeper errors
147145
*/
148146
public AtomicValue<byte[]> trySet(final byte[] newValue) throws Exception {
149-
MutableAtomicValue<byte[]> result = new MutableAtomicValue<byte[]>(null, null, false);
147+
MutableAtomicValue<byte[]> result = new MutableAtomicValue<>(null, null, false);
150148

151-
MakeValue makeValue = new MakeValue() {
152-
@Override
153-
public byte[] makeFrom(byte[] previous) {
154-
return newValue;
155-
}
156-
};
149+
MakeValue makeValue = previous -> newValue;
157150
tryOptimistic(result, makeValue);
158151
if (!result.succeeded() && (mutex != null)) {
159152
tryWithMutex(result, makeValue);
@@ -181,7 +174,7 @@ public boolean initialize(byte[] value) throws Exception {
181174
}
182175

183176
AtomicValue<byte[]> trySet(MakeValue makeValue) throws Exception {
184-
MutableAtomicValue<byte[]> result = new MutableAtomicValue<byte[]>(null, null, false);
177+
MutableAtomicValue<byte[]> result = new MutableAtomicValue<>(null, null, false);
185178

186179
tryOptimistic(result, makeValue);
187180
if (!result.succeeded() && (mutex != null)) {
@@ -204,7 +197,7 @@ RuntimeException createCorruptionException(byte[] bytes) {
204197
str.append("0x").append(Integer.toHexString((b & 0xff)));
205198
}
206199
str.append(']');
207-
return new RuntimeException(String.format("Corrupted data for node \"%s\": %s", path, str.toString()));
200+
return new RuntimeException(String.format("Corrupted data for node \"%s\": %s", path, str));
208201
}
209202

210203
private boolean getCurrentValue(MutableAtomicValue<byte[]> result, Stat stat) throws Exception {
@@ -284,11 +277,9 @@ private boolean tryOnce(MutableAtomicValue<byte[]> result, MakeValue makeValue)
284277
}
285278
result.postValue = Arrays.copyOf(newValue, newValue.length);
286279
success = true;
287-
} catch (KeeperException.NodeExistsException e) {
288-
// do Retry
289-
} catch (KeeperException.BadVersionException e) {
290-
// do Retry
291-
} catch (KeeperException.NoNodeException e) {
280+
} catch (KeeperException.NodeExistsException
281+
| KeeperException.BadVersionException
282+
| KeeperException.NoNodeException e) {
292283
// do Retry
293284
}
294285

0 commit comments

Comments
 (0)