Skip to content

Commit b0a73ee

Browse files
committed
Reformat code with Palantir Java Format
1 parent 7dd5801 commit b0a73ee

27 files changed

+558
-836
lines changed

pom.xml

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -128,10 +128,9 @@
128128
<version>3.2.0</version>
129129
<configuration>
130130
<java>
131-
<googleJavaFormat>
132-
<version>1.33.0</version>
133-
<style>AOSP</style>
134-
</googleJavaFormat>
131+
<palantirJavaFormat>
132+
<version>2.85.0</version>
133+
</palantirJavaFormat>
135134
<removeUnusedImports />
136135
<formatAnnotations />
137136
</java>

src/main/java/io/apitally/common/ApitallyClient.java

Lines changed: 78 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -44,18 +44,16 @@ public enum HubRequestStatus {
4444
private static final int INITIAL_PERIOD_SECONDS = 3600;
4545
private static final int MAX_QUEUE_TIME_SECONDS = 3600;
4646
private static final int REQUEST_TIMEOUT_SECONDS = 10;
47-
private static final String HUB_BASE_URL =
48-
Optional.ofNullable(System.getenv("APITALLY_HUB_BASE_URL"))
49-
.filter(s -> !s.trim().isEmpty())
50-
.orElse("https://hub.apitally.io");
47+
private static final String HUB_BASE_URL = Optional.ofNullable(System.getenv("APITALLY_HUB_BASE_URL"))
48+
.filter(s -> !s.trim().isEmpty())
49+
.orElse("https://hub.apitally.io");
5150

5251
private static final Logger logger = LoggerFactory.getLogger(ApitallyClient.class);
53-
private static final RetryTemplate retryTemplate =
54-
RetryTemplate.builder()
55-
.maxAttempts(3)
56-
.exponentialBackoff(Duration.ofSeconds(1), 2, Duration.ofSeconds(4), true)
57-
.retryOn(RetryableHubRequestException.class)
58-
.build();
52+
private static final RetryTemplate retryTemplate = RetryTemplate.builder()
53+
.maxAttempts(3)
54+
.exponentialBackoff(Duration.ofSeconds(1), 2, Duration.ofSeconds(4), true)
55+
.retryOn(RetryableHubRequestException.class)
56+
.build();
5957

6058
private final String clientId;
6159
private final String env;
@@ -87,9 +85,7 @@ public ApitallyClient(String clientId, String env, RequestLoggingConfig requestL
8785
this.requestCounter = new RequestCounter();
8886
this.requestLogger = new RequestLogger(requestLoggingConfig);
8987
this.spanCollector =
90-
new SpanCollector(
91-
requestLoggingConfig.isEnabled()
92-
&& requestLoggingConfig.isTracingEnabled());
88+
new SpanCollector(requestLoggingConfig.isEnabled() && requestLoggingConfig.isTracingEnabled());
9389
this.validationErrorCounter = new ValidationErrorCounter();
9490
this.serverErrorCounter = new ServerErrorCounter();
9591
this.consumerRegistry = new ConsumerRegistry();
@@ -128,36 +124,32 @@ private void sendStartupData() {
128124
if (startupData == null) {
129125
return;
130126
}
131-
HttpRequest request =
132-
HttpRequest.newBuilder()
133-
.uri(getHubUrl("startup"))
134-
.header("Content-Type", "application/json")
135-
.POST(HttpRequest.BodyPublishers.ofString(startupData.toJSON()))
136-
.build();
137-
sendHubRequest(request)
138-
.thenAccept(
139-
status -> {
140-
if (status == HubRequestStatus.OK) {
141-
startupDataSent = true;
142-
startupData = null;
143-
} else if (status == HubRequestStatus.VALIDATION_ERROR) {
144-
startupDataSent = false;
145-
startupData = null;
146-
} else {
147-
startupDataSent = false;
148-
}
149-
});
127+
HttpRequest request = HttpRequest.newBuilder()
128+
.uri(getHubUrl("startup"))
129+
.header("Content-Type", "application/json")
130+
.POST(HttpRequest.BodyPublishers.ofString(startupData.toJSON()))
131+
.build();
132+
sendHubRequest(request).thenAccept(status -> {
133+
if (status == HubRequestStatus.OK) {
134+
startupDataSent = true;
135+
startupData = null;
136+
} else if (status == HubRequestStatus.VALIDATION_ERROR) {
137+
startupDataSent = false;
138+
startupData = null;
139+
} else {
140+
startupDataSent = false;
141+
}
142+
});
150143
}
151144

152145
private void sendSyncData() {
153-
SyncData data =
154-
new SyncData(
155-
instanceLock.getInstanceUuid(),
156-
requestCounter.getAndResetRequests(),
157-
validationErrorCounter.getAndResetValidationErrors(),
158-
serverErrorCounter.getAndResetServerErrors(),
159-
consumerRegistry.getAndResetConsumers(),
160-
resourceMonitor.getCpuMemoryUsage());
146+
SyncData data = new SyncData(
147+
instanceLock.getInstanceUuid(),
148+
requestCounter.getAndResetRequests(),
149+
validationErrorCounter.getAndResetValidationErrors(),
150+
serverErrorCounter.getAndResetServerErrors(),
151+
consumerRegistry.getAndResetConsumers(),
152+
resourceMonitor.getCpuMemoryUsage());
161153
syncDataQueue.offer(data);
162154

163155
int i = 0;
@@ -170,12 +162,11 @@ private void sendSyncData() {
170162
// Add random delay between retries
171163
Thread.sleep(100 + random.nextInt(400));
172164
}
173-
HttpRequest request =
174-
HttpRequest.newBuilder()
175-
.uri(getHubUrl("sync"))
176-
.header("Content-Type", "application/json")
177-
.POST(HttpRequest.BodyPublishers.ofString(payload.toJSON()))
178-
.build();
165+
HttpRequest request = HttpRequest.newBuilder()
166+
.uri(getHubUrl("sync"))
167+
.header("Content-Type", "application/json")
168+
.POST(HttpRequest.BodyPublishers.ofString(payload.toJSON()))
169+
.build();
179170
HubRequestStatus status = sendHubRequest(request).join();
180171
if (status == HubRequestStatus.RETRYABLE_ERROR) {
181172
syncDataQueue.offer(payload);
@@ -204,12 +195,11 @@ private void sendLogData() {
204195
}
205196
}
206197
try (InputStream inputStream = logFile.getInputStream()) {
207-
HttpRequest request =
208-
HttpRequest.newBuilder()
209-
.uri(getHubUrl("log", "uuid=" + logFile.getUuid().toString()))
210-
.header("Content-Type", "application/octet-stream")
211-
.POST(HttpRequest.BodyPublishers.ofInputStream(() -> inputStream))
212-
.build();
198+
HttpRequest request = HttpRequest.newBuilder()
199+
.uri(getHubUrl("log", "uuid=" + logFile.getUuid().toString()))
200+
.header("Content-Type", "application/octet-stream")
201+
.POST(HttpRequest.BodyPublishers.ofInputStream(() -> inputStream))
202+
.build();
213203
HubRequestStatus status = sendHubRequest(request).join();
214204
if (status == HubRequestStatus.PAYMENT_REQUIRED) {
215205
requestLogger.clear();
@@ -231,84 +221,62 @@ private void sendLogData() {
231221
}
232222

233223
public CompletableFuture<HubRequestStatus> sendHubRequest(HttpRequest request) {
234-
return CompletableFuture.supplyAsync(
235-
() -> {
224+
return CompletableFuture.supplyAsync(() -> {
225+
try {
226+
return retryTemplate.execute(context -> {
236227
try {
237-
return retryTemplate.execute(
238-
context -> {
239-
try {
240-
logger.debug(
241-
"Sending request to Apitally hub: {}",
242-
request.uri());
243-
HttpResponse<String> response =
244-
httpClient.send(
245-
request,
246-
HttpResponse.BodyHandlers.ofString());
247-
if (response.statusCode() >= 200
248-
&& response.statusCode() < 300) {
249-
return HubRequestStatus.OK;
250-
} else if (response.statusCode() == 402) {
251-
return HubRequestStatus.PAYMENT_REQUIRED;
252-
} else if (response.statusCode() == 404) {
253-
enabled = false;
254-
stopSync();
255-
requestLogger.close();
256-
logger.error(
257-
"Invalid Apitally client ID: {}", clientId);
258-
return HubRequestStatus.INVALID_CLIENT_ID;
259-
} else if (response.statusCode() == 422) {
260-
logger.error(
261-
"Received validation error from Apitally hub: {}",
262-
response.body());
263-
return HubRequestStatus.VALIDATION_ERROR;
264-
} else {
265-
throw new RetryableHubRequestException(
266-
"Hub request failed with status code "
267-
+ response.statusCode());
268-
}
269-
} catch (Exception e) {
270-
throw new RetryableHubRequestException(
271-
"Hub request failed with exception: "
272-
+ e.getMessage());
273-
}
274-
});
228+
logger.debug("Sending request to Apitally hub: {}", request.uri());
229+
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
230+
if (response.statusCode() >= 200 && response.statusCode() < 300) {
231+
return HubRequestStatus.OK;
232+
} else if (response.statusCode() == 402) {
233+
return HubRequestStatus.PAYMENT_REQUIRED;
234+
} else if (response.statusCode() == 404) {
235+
enabled = false;
236+
stopSync();
237+
requestLogger.close();
238+
logger.error("Invalid Apitally client ID: {}", clientId);
239+
return HubRequestStatus.INVALID_CLIENT_ID;
240+
} else if (response.statusCode() == 422) {
241+
logger.error("Received validation error from Apitally hub: {}", response.body());
242+
return HubRequestStatus.VALIDATION_ERROR;
243+
} else {
244+
throw new RetryableHubRequestException(
245+
"Hub request failed with status code " + response.statusCode());
246+
}
275247
} catch (Exception e) {
276-
logger.error("Error sending request to Apitally hub", e);
277-
return HubRequestStatus.RETRYABLE_ERROR;
248+
throw new RetryableHubRequestException("Hub request failed with exception: " + e.getMessage());
278249
}
279250
});
251+
} catch (Exception e) {
252+
logger.error("Error sending request to Apitally hub", e);
253+
return HubRequestStatus.RETRYABLE_ERROR;
254+
}
255+
});
280256
}
281257

282258
public void startSync() {
283259
if (scheduler == null) {
284-
scheduler =
285-
Executors.newSingleThreadScheduledExecutor(
286-
r -> {
287-
Thread thread = new Thread(r, "apitally-sync");
288-
thread.setDaemon(true);
289-
return thread;
290-
});
260+
scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
261+
Thread thread = new Thread(r, "apitally-sync");
262+
thread.setDaemon(true);
263+
return thread;
264+
});
291265
}
292266

293267
if (syncTask != null) {
294268
syncTask.cancel(false);
295269
}
296270

297271
// Start with shorter initial sync interval
298-
syncTask =
299-
scheduler.scheduleAtFixedRate(
300-
this::sync, 0, INITIAL_SYNC_INTERVAL_SECONDS, TimeUnit.SECONDS);
272+
syncTask = scheduler.scheduleAtFixedRate(this::sync, 0, INITIAL_SYNC_INTERVAL_SECONDS, TimeUnit.SECONDS);
301273

302274
// Schedule a one-time task to switch to regular sync interval
303275
scheduler.schedule(
304276
() -> {
305277
syncTask.cancel(false);
306-
syncTask =
307-
scheduler.scheduleAtFixedRate(
308-
this::sync,
309-
SYNC_INTERVAL_SECONDS,
310-
SYNC_INTERVAL_SECONDS,
311-
TimeUnit.SECONDS);
278+
syncTask = scheduler.scheduleAtFixedRate(
279+
this::sync, SYNC_INTERVAL_SECONDS, SYNC_INTERVAL_SECONDS, TimeUnit.SECONDS);
312280
},
313281
INITIAL_PERIOD_SECONDS,
314282
TimeUnit.SECONDS);

src/main/java/io/apitally/common/ConsumerRegistry.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,9 +56,7 @@ public void addOrUpdateConsumer(Consumer consumer) {
5656
}
5757

5858
if (hasChanges) {
59-
consumers.put(
60-
consumer.getIdentifier(),
61-
new Consumer(consumer.getIdentifier(), newName, newGroup));
59+
consumers.put(consumer.getIdentifier(), new Consumer(consumer.getIdentifier(), newName, newGroup));
6260
updated.add(consumer.getIdentifier());
6361
}
6462
}

src/main/java/io/apitally/common/InstanceLock.java

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,8 @@ static InstanceLock create(String clientId, String env, Path lockDir) {
5555
Path lockPath = lockDir.resolve("instance_" + appEnvHash + "_" + slot + ".lock");
5656
FileChannel channel = null;
5757
try {
58-
channel =
59-
FileChannel.open(
60-
lockPath,
61-
StandardOpenOption.CREATE,
62-
StandardOpenOption.READ,
63-
StandardOpenOption.WRITE);
58+
channel = FileChannel.open(
59+
lockPath, StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
6460

6561
FileLock lock = channel.tryLock();
6662
if (lock == null) {
@@ -69,9 +65,9 @@ static InstanceLock create(String clientId, String env, Path lockDir) {
6965
}
7066

7167
FileTime lastModified = Files.getLastModifiedTime(lockPath);
72-
boolean tooOld =
73-
Duration.between(lastModified.toInstant(), Instant.now()).getSeconds()
74-
> MAX_LOCK_AGE_SECONDS;
68+
boolean tooOld = Duration.between(lastModified.toInstant(), Instant.now())
69+
.getSeconds()
70+
> MAX_LOCK_AGE_SECONDS;
7571

7672
String existingUuid = readChannel(channel);
7773
UUID uuid = parseUuid(existingUuid);
@@ -120,8 +116,7 @@ private static UUID parseUuid(String s) {
120116
}
121117
}
122118

123-
private static String getAppEnvHash(String clientId, String env)
124-
throws NoSuchAlgorithmException {
119+
private static String getAppEnvHash(String clientId, String env) throws NoSuchAlgorithmException {
125120
MessageDigest digest = MessageDigest.getInstance("SHA-256");
126121
byte[] hash = digest.digest((clientId + ":" + env).getBytes(StandardCharsets.UTF_8));
127122
return HexFormat.of().formatHex(hash, 0, 4);

src/main/java/io/apitally/common/RequestCounter.java

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ public void addRequest(
3131
long responseTime,
3232
long requestSize,
3333
long responseSize) {
34-
String key =
35-
String.join("|", consumer, method.toUpperCase(), path, String.valueOf(statusCode));
34+
String key = String.join("|", consumer, method.toUpperCase(), path, String.valueOf(statusCode));
3635

3736
// Increment request count
3837
requestCounts.merge(key, 1, Integer::sum);
@@ -73,25 +72,21 @@ public List<Requests> getAndResetRequests() {
7372
String path = parts[2];
7473
int statusCode = Integer.parseInt(parts[3]);
7574

76-
Map<Integer, Integer> responseTimeMap =
77-
responseTimes.getOrDefault(key, new ConcurrentHashMap<>());
78-
Map<Integer, Integer> requestSizeMap =
79-
requestSizes.getOrDefault(key, new ConcurrentHashMap<>());
80-
Map<Integer, Integer> responseSizeMap =
81-
responseSizes.getOrDefault(key, new ConcurrentHashMap<>());
75+
Map<Integer, Integer> responseTimeMap = responseTimes.getOrDefault(key, new ConcurrentHashMap<>());
76+
Map<Integer, Integer> requestSizeMap = requestSizes.getOrDefault(key, new ConcurrentHashMap<>());
77+
Map<Integer, Integer> responseSizeMap = responseSizes.getOrDefault(key, new ConcurrentHashMap<>());
8278

83-
Requests item =
84-
new Requests(
85-
consumer,
86-
method,
87-
path,
88-
statusCode,
89-
entry.getValue(),
90-
requestSizeSums.getOrDefault(key, 0L),
91-
responseSizeSums.getOrDefault(key, 0L),
92-
responseTimeMap,
93-
requestSizeMap,
94-
responseSizeMap);
79+
Requests item = new Requests(
80+
consumer,
81+
method,
82+
path,
83+
statusCode,
84+
entry.getValue(),
85+
requestSizeSums.getOrDefault(key, 0L),
86+
responseSizeSums.getOrDefault(key, 0L),
87+
responseTimeMap,
88+
requestSizeMap,
89+
responseSizeMap);
9590
data.add(item);
9691
}
9792

0 commit comments

Comments
 (0)