Skip to content

Commit 46dbb48

Browse files
committed
Cleaned up code
1 parent 548d06d commit 46dbb48

File tree

12 files changed

+112
-62
lines changed

12 files changed

+112
-62
lines changed

src/main/java/net/foulest/ospreyproxy/ProxyHandler.java

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import net.foulest.ospreyproxy.util.*;
2929
import net.foulest.ospreyproxy.util.list.Descriptor;
3030
import net.foulest.ospreyproxy.util.list.LocalListUtil;
31+
import net.foulest.ospreyproxy.util.stats.StatsUtil;
3132
import org.apache.hc.client5.http.config.ConnectionConfig;
3233
import org.apache.hc.client5.http.config.RequestConfig;
3334
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
@@ -105,6 +106,9 @@ public class ProxyHandler {
105106

106107
/**
107108
* Constructor for ProxyHandler. Spring injects every {@link Provider} bean automatically.
109+
*
110+
* @param providers All registered providers, injected by Spring.
111+
* @param checkEndpoint The CheckEndpoint provider, injected by Spring.
108112
*/
109113
public ProxyHandler(@NonNull List<Provider> providers, @NonNull CheckEndpoint checkEndpoint) {
110114
this.checkEndpoint = checkEndpoint;
@@ -120,7 +124,7 @@ public ProxyHandler(@NonNull List<Provider> providers, @NonNull CheckEndpoint ch
120124
controlD = getDnsProvider("controld-security");
121125
quad9 = getDnsProvider("quad9");
122126
switchCh = getDnsProvider("switch-ch");
123-
phishingDatabase = providersByEndpointName.get(Descriptor.PHISHING_DATABASE.endpointName);
127+
phishingDatabase = providersByEndpointName.get(Descriptor.PHISHING_DATABASE.getEndpointName());
124128

125129
// Pre-warm Jackson type metadata
126130
JacksonUtil.MAPPER.constructType(Map.class);
@@ -132,6 +136,11 @@ public ProxyHandler(@NonNull List<Provider> providers, @NonNull CheckEndpoint ch
132136
* Dynamic endpoint for all non-CheckEndpoint providers.
133137
* Routes to the provider whose {@link Provider#getEndpointName()} matches {@code providerName}.
134138
* Keep @RequestBody(required = false) for rate-limiting.
139+
*
140+
* @param providerName The path variable extracted from the URL, used to look up the provider.
141+
* @param body The raw request body bytes, passed to the provider for validation and forwarding.
142+
* @param request The incoming servlet request, used for IP extraction and header validation.
143+
* @return A {@link ResponseEntity} containing the provider's response or an appropriate error status.
135144
*/
136145
@PostMapping(value = "/{providerName}",
137146
consumes = MediaType.APPLICATION_JSON_VALUE,
@@ -150,6 +159,10 @@ public ResponseEntity<String> handleProvider(@PathVariable String providerName,
150159
/**
151160
* Dedicated /check endpoint for aggregate lookups to all non-premium providers.
152161
* Keep @RequestBody(required = false) for rate-limiting.
162+
*
163+
* @param body The raw request body bytes, passed to the provider for validation and forwarding.
164+
* @param request The incoming servlet request, used for IP extraction and header validation.
165+
* @return A {@link ResponseEntity} containing the aggregate JSON result or an appropriate error status.
153166
*/
154167
@PostMapping(value = "/check",
155168
consumes = MediaType.APPLICATION_JSON_VALUE,
@@ -219,7 +232,7 @@ private ResponseEntity<String> proxyRequest(byte[] bodyBytes,
219232
if (result == LookupResult.RATE_LIMITED) {
220233
return ErrorUtil.RESP_429;
221234
}
222-
return resultResponse(result, providerName, host);
235+
return resultResponse(result, providerName);
223236
}
224237

225238
// Local list providers check against an in-memory domain set.
@@ -231,7 +244,7 @@ private ResponseEntity<String> proxyRequest(byte[] bodyBytes,
231244
if (result == LookupResult.RATE_LIMITED) {
232245
return ErrorUtil.RESP_429;
233246
}
234-
return resultResponse(result, providerName, host);
247+
return resultResponse(result, providerName);
235248
}
236249

237250
// API providers require HTTP_CLIENT which lives here, so execution stays in
@@ -268,7 +281,7 @@ private static ResponseEntity<String> executeUpstream(@NonNull Provider provider
268281

269282
if (cached != null) {
270283
StatsUtil.recordCacheHit();
271-
return resultResponse(cached, providerName, forwardUrl);
284+
return resultResponse(cached, providerName);
272285
}
273286

274287
StatsUtil.recordCacheMiss();
@@ -353,7 +366,7 @@ private static ResponseEntity<String> executeUpstream(@NonNull Provider provider
353366
if (provider instanceof AbstractProvider ap) {
354367
ap.putCachedResult(forwardUrl, result);
355368
}
356-
return resultResponse(result, providerName, forwardUrl);
369+
return resultResponse(result, providerName);
357370
});
358371
} catch (SocketTimeoutException | ConnectionRequestTimeoutException | NoHttpResponseException e) {
359372
log.error("[{}] Upstream request timed out ({})", providerName, e.getClass().getName());
@@ -374,21 +387,16 @@ private static ResponseEntity<String> executeUpstream(@NonNull Provider provider
374387
*
375388
* @param result The result to serialize.
376389
* @param providerName The provider display name for error logging.
377-
* @param lookupStr The lookup string (host or URL) for error logging.
378390
* @return A {@link ResponseEntity} with the JSON body, or a 502 on serialization failure.
379391
*/
380392
@SuppressWarnings("NestedMethodCall")
381393
private static @NonNull ResponseEntity<String> resultResponse(@NonNull LookupResult result,
382-
@NonNull String providerName,
383-
@NonNull String lookupStr) {
394+
@NonNull String providerName) {
384395
try {
385-
String responseBody = JacksonUtil.MAPPER.writeValueAsString(
386-
Map.of("result", result.getValue())
387-
);
396+
String responseBody = JacksonUtil.MAPPER.writeValueAsString(Map.of("result", result.getValue()));
388397
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(responseBody);
389398
} catch (@SuppressWarnings("OverlyBroadCatchBlock") Exception e) {
390-
log.error("[{}] Failed to serialize result: {} ({})",
391-
providerName, e.getMessage(), e.getClass().getName());
399+
log.error("[{}] Failed to serialize result: {} ({})", providerName, e.getMessage(), e.getClass().getName());
392400
return ErrorUtil.RESP_502;
393401
}
394402
}

src/main/java/net/foulest/ospreyproxy/exceptions/GlobalExceptionHandler.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,11 +53,11 @@ public ResponseEntity<String> handleStatusCode(@NonNull StatusCodeException ex)
5353
* Handles requests whose body exceeds the configured size limit.
5454
* Tomcat rejects these before any controller code runs.
5555
*
56-
* @param ex The exception to handle.
56+
* @param ignored The exception to handle (ignored).
5757
* @return A 400 Bad Request response indicating the body was too large.
5858
*/
5959
@ExceptionHandler(MaxUploadSizeExceededException.class)
60-
public ResponseEntity<String> handleMaxUploadSize(@NonNull MaxUploadSizeExceededException ex) {
60+
public ResponseEntity<String> handleMaxUploadSize(@NonNull MaxUploadSizeExceededException ignored) {
6161
log.warn("Request body exceeded size limit");
6262
return ErrorUtil.RESP_400;
6363
}

src/main/java/net/foulest/ospreyproxy/providers/AbstractDNSProvider.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@
2222
import net.foulest.ospreyproxy.util.CooldownUtil;
2323
import net.foulest.ospreyproxy.util.HttpClientFactory;
2424
import net.foulest.ospreyproxy.util.JacksonUtil;
25-
import net.foulest.ospreyproxy.util.StatsUtil;
2625
import net.foulest.ospreyproxy.util.dns.Accept;
2726
import net.foulest.ospreyproxy.util.dns.DNSFormat;
2827
import net.foulest.ospreyproxy.util.dns.DNSUtil;
28+
import net.foulest.ospreyproxy.util.stats.StatsUtil;
2929
import org.apache.hc.client5.http.classic.methods.HttpGet;
3030
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
3131
import org.apache.hc.core5.http.ClassicHttpResponse;

src/main/java/net/foulest/ospreyproxy/providers/api/AlphaMountain.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ public boolean isEnabled() {
125125
Object categoriesObj = categoryMap.get("categories");
126126

127127
if (!(categoriesObj instanceof List<?> categories) || categories.isEmpty()) {
128-
log.info("[{}] No categories found", displayName);
128+
log.warn("[{}] No categories found", displayName);
129129
return LookupResult.FAILED;
130130
}
131131

src/main/java/net/foulest/ospreyproxy/providers/list/LocalListProvider.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,9 @@
2020
import lombok.RequiredArgsConstructor;
2121
import net.foulest.ospreyproxy.providers.AbstractProvider;
2222
import net.foulest.ospreyproxy.result.LookupResult;
23-
import net.foulest.ospreyproxy.util.StatsUtil;
2423
import net.foulest.ospreyproxy.util.list.Descriptor;
2524
import net.foulest.ospreyproxy.util.list.LocalListUtil;
25+
import net.foulest.ospreyproxy.util.stats.StatsUtil;
2626
import org.jspecify.annotations.NonNull;
2727

2828
/**
@@ -41,12 +41,12 @@ public class LocalListProvider extends AbstractProvider {
4141

4242
@Override
4343
public @NonNull String getDisplayName() {
44-
return descriptor.shortName;
44+
return descriptor.getShortName();
4545
}
4646

4747
@Override
4848
public @NonNull String getEndpointName() {
49-
return descriptor.endpointName;
49+
return descriptor.getEndpointName();
5050
}
5151

5252
@Override

src/main/java/net/foulest/ospreyproxy/util/CooldownUtil.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
* Utility class for managing cooldowns of providers after receiving 429 or 5xx responses.
1717
*/
1818
@Slf4j
19+
@SuppressWarnings("MissingJavadoc")
1920
@NoArgsConstructor(access = AccessLevel.PRIVATE)
2021
public final class CooldownUtil {
2122

src/main/java/net/foulest/ospreyproxy/util/ErrorUtil.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
/**
2828
* Utility class for building standardized error responses in the OspreyProxy application.
2929
*/
30+
@SuppressWarnings("MissingJavadoc")
3031
@NoArgsConstructor(access = AccessLevel.PRIVATE)
3132
public final class ErrorUtil {
3233

src/main/java/net/foulest/ospreyproxy/util/JacksonUtil.java

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,14 @@
3131
import java.util.Map;
3232

3333
/**
34-
* Utility class for Jackson ObjectMapper and pre-resolved JavaType instances to optimize JSON parsing and validation.
34+
* Utility class for Jackson JSON processing.
3535
*/
3636
@NoArgsConstructor(access = AccessLevel.PRIVATE)
3737
public final class JacksonUtil {
3838

39-
// Jackson mapper for parsing request bodies and validating upstream responses
39+
/**
40+
* The shared {@link ObjectMapper} instance for parsing request bodies and validating upstream responses.
41+
*/
4042
public static final ObjectMapper MAPPER = JsonMapper.builder(JsonFactory.builder()
4143
.streamReadConstraints(StreamReadConstraints.builder()
4244
.maxNumberLength(1000)
@@ -47,19 +49,25 @@ public final class JacksonUtil {
4749
.build())
4850
.build();
4951

50-
// Pre-resolved JavaType for Map<String, String> to avoid construction overhead
52+
/**
53+
* The pre-resolved {@link JavaType} for {@code Map<String, String>} to avoid construction overhead.
54+
*/
5155
static final JavaType MAP_TYPE_STRING = MAPPER.constructType(
5256
new TypeReference<Map<String, String>>() {
5357
}
5458
);
5559

56-
// Pre-resolved JavaType for Map<String, Object> to avoid construction overhead
60+
/**
61+
* The pre-resolved {@link JavaType} for {@code Map<String, Object>} to avoid construction overhead.
62+
*/
5763
public static final JavaType MAP_TYPE_OBJECT = MAPPER.constructType(
5864
new TypeReference<Map<String, Object>>() {
5965
}
6066
);
6167

62-
// Pre-resolved JavaType for List<String> to avoid construction overhead
68+
/**
69+
* The pre-resolved JavaType for {@code List<String>} to avoid construction overhead.
70+
*/
6371
public static final JavaType LIST_TYPE = MAPPER.constructType(
6472
new TypeReference<List<String>>() {
6573
}

src/main/java/net/foulest/ospreyproxy/util/list/Descriptor.java

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,13 @@
1818
package net.foulest.ospreyproxy.util.list;
1919

2020
import lombok.AllArgsConstructor;
21+
import lombok.Getter;
2122
import net.foulest.ospreyproxy.result.LookupResult;
2223

2324
/**
2425
* Represents a descriptor for a list provider, containing all necessary information to fetch and interpret the list.
2526
*/
27+
@Getter
2628
@AllArgsConstructor
2729
public enum Descriptor {
2830

@@ -50,26 +52,33 @@ public enum Descriptor {
5052
120L
5153
);
5254

53-
final String url;
54-
final Format format;
55+
/**
56+
* The URL from which to fetch the list data.
57+
*/
58+
private final String url;
59+
60+
/**
61+
* The format of the list, which determines how it should be parsed.
62+
*/
63+
private final Format format;
5564

5665
/**
5766
* A human-readable name for this list, used in logging.
5867
*/
59-
public final String shortName;
68+
private final String shortName;
6069

6170
/**
6271
* The endpoint name for this list, used in configuration and routing.
6372
*/
64-
public final String endpointName;
73+
private final String endpointName;
6574

6675
/**
6776
* The type of result to return when a domain is found in this list.
6877
*/
69-
public final LookupResult resultType;
78+
private final LookupResult resultType;
7079

7180
/**
7281
* The interval in seconds at which this list should be refreshed.
7382
*/
74-
public final long refreshIntervalSeconds;
83+
private final long refreshIntervalSeconds;
7584
}

src/main/java/net/foulest/ospreyproxy/util/list/LocalListUtil.java

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
/**
4343
* Utility class for managing local lists of domains fetched from external providers.
4444
*/
45+
@SuppressWarnings("NestedMethodCall")
4546
@Slf4j
4647
@Component
4748
public final class LocalListUtil {
@@ -68,7 +69,7 @@ public final class LocalListUtil {
6869
Map<String, Descriptor> map = new HashMap<>();
6970

7071
for (Descriptor descriptor : Descriptor.values()) {
71-
map.put(descriptor.endpointName, descriptor);
72+
map.put(descriptor.getEndpointName(), descriptor);
7273
}
7374

7475
descriptorsByEndpointName = Collections.unmodifiableMap(map);
@@ -88,7 +89,7 @@ public void init() {
8889
scheduler.scheduleWithFixedDelay(
8990
() -> fetchAndUpdate(descriptor),
9091
0L,
91-
descriptor.refreshIntervalSeconds,
92+
descriptor.getRefreshIntervalSeconds(),
9293
TimeUnit.SECONDS
9394
);
9495
}
@@ -130,10 +131,10 @@ public void destroy() {
130131
Set<String> domainSet = ref.get().domainSet();
131132

132133
if (domainSet == null) {
133-
log.warn("[{}] List not yet loaded; skipping pending lookup", descriptor.shortName);
134+
log.warn("[{}] List not yet loaded; skipping pending lookup", descriptor.getShortName());
134135
return LookupResult.FAILED;
135136
}
136-
return isHostInSet(domainSet, host) ? descriptor.resultType : LookupResult.ALLOWED;
137+
return isHostInSet(domainSet, host) ? descriptor.getResultType() : LookupResult.ALLOWED;
137138
}
138139

139140
/**
@@ -183,7 +184,7 @@ private static void fetchAndUpdate(@NonNull Descriptor descriptor) {
183184
}
184185
} catch (Exception e) {
185186
log.warn("[{}] Failed to fetch list update: {} ({})",
186-
descriptor.shortName, e.getMessage(), e.getClass().getName());
187+
descriptor.getShortName(), e.getMessage(), e.getClass().getName());
187188
}
188189
}
189190

@@ -202,7 +203,7 @@ private static void fetchAndUpdate(@NonNull Descriptor descriptor) {
202203
@SuppressWarnings({"NestedMethodCall", "ProhibitedExceptionDeclared"})
203204
private static @Nullable FetchResult fetchRaw(@NonNull Descriptor descriptor,
204205
@Nullable String currentEtag) throws Exception {
205-
HttpGet request = new HttpGet(descriptor.url);
206+
HttpGet request = new HttpGet(descriptor.getUrl());
206207
request.addHeader("Accept", "application/json, text/plain, */*");
207208

208209
if (currentEtag != null) {
@@ -255,12 +256,12 @@ private static void applyContent(@NonNull Descriptor descriptor,
255256
@Nullable String etag) {
256257
Set<String> newSet;
257258
try {
258-
newSet = descriptor.format == Format.TEXT
259+
newSet = descriptor.getFormat() == Format.TEXT
259260
? parsePlainText(rawContent)
260261
: parseJson(rawContent);
261262
} catch (@SuppressWarnings("OverlyBroadCatchBlock") Exception e) {
262263
log.warn("[{}] Failed to parse list; keeping current: {} ({})",
263-
descriptor.shortName, e.getMessage(), e.getClass().getName());
264+
descriptor.getShortName(), e.getMessage(), e.getClass().getName());
264265
return;
265266
}
266267

0 commit comments

Comments
 (0)