Skip to content

Commit d32f516

Browse files
committed
Refactor HTTP requests to use HttpClient and remove deprecated code
- Updated NameFetcher and PlayerUtils to use HttpClient for API calls. - Removed unused imports and deprecated methods across multiple files. - Enhanced error handling for HTTP responses in Updater and other classes.
1 parent 2f3221b commit d32f516

11 files changed

Lines changed: 275 additions & 342 deletions

File tree

SimpleAPI/src/main/java/com/bencodez/simpleapi/file/BungeeJsonFile.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import java.io.IOException;
77
import java.util.ArrayList;
88
import java.util.List;
9-
import java.util.Map;
109

1110
import com.google.gson.Gson;
1211
import com.google.gson.GsonBuilder;

SimpleAPI/src/main/java/com/bencodez/simpleapi/file/CaseInsensitiveFileConfiguration.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,6 @@ public boolean getBoolean(String path, boolean def) {
164164
return rp == null ? def : rp.section.getBoolean(rp.key, def);
165165
}
166166

167-
@SuppressWarnings("unchecked")
168167
public List<?> getList(String path) {
169168
ResolvedPath rp = resolvePath(path);
170169
if (rp == null)

SimpleAPI/src/main/java/com/bencodez/simpleapi/file/annotation/AnnotationHandler.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import java.util.HashSet;
66
import java.util.List;
77
import java.util.Set;
8-
import java.util.concurrent.TimeUnit;
98

109
import org.bukkit.configuration.ConfigurationSection;
1110

SimpleAPI/src/main/java/com/bencodez/simpleapi/metrics/BStatsMetrics.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,7 @@ private void sendData(JsonObjectBuilder.JsonObject data) throws Exception {
540540
infoLogger.accept("Sent bStats metrics data: " + data.toString());
541541
}
542542
String url = String.format(REPORT_URL, platform);
543+
@SuppressWarnings("deprecation")
543544
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
544545
// Compress the data to save bandwidth
545546
byte[] compressedData = compress(data.toString());

SimpleAPI/src/main/java/com/bencodez/simpleapi/nms/ReflectionUtils.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ public static Class<?> getClassForName(String name) {
3333

3434
public static Object getFieldValue(Field field, Object object) {
3535
try {
36+
@SuppressWarnings("deprecation")
3637
boolean a = !field.isAccessible();
3738
if (a) {
3839
field.setAccessible(true);
@@ -48,6 +49,7 @@ public static Object getFieldValue(Field field, Object object) {
4849
}
4950
}
5051

52+
@SuppressWarnings("deprecation")
5153
public static Object invokeMethod(Method method, Object object, Object... args) {
5254
try {
5355
boolean a = !method.isAccessible();
@@ -89,6 +91,7 @@ public static int removeModifier(Object fieldOrMethod, int modifierToRemove) {
8991
*/
9092
public static Object setField(Field field, Object object, Object newValue) {
9193
try {
94+
@SuppressWarnings("deprecation")
9295
boolean a = !field.isAccessible();
9396
if (a) {
9497
field.setAccessible(true);
Lines changed: 65 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,31 @@
11
package com.bencodez.simpleapi.player;
22

3-
import java.io.InputStreamReader;
4-
import java.net.HttpURLConnection;
5-
import java.net.URL;
3+
import java.io.IOException;
4+
import java.net.URI;
5+
import java.net.http.HttpClient;
6+
import java.net.http.HttpRequest;
7+
import java.net.http.HttpResponse;
8+
import java.time.Duration;
69
import java.util.HashMap;
710
import java.util.List;
811
import java.util.Map;
912
import java.util.UUID;
1013
import java.util.concurrent.Callable;
1114

12-
import com.bencodez.simpleapi.json.JsonParser;
1315
import com.google.common.collect.ImmutableList;
16+
import com.google.gson.JsonElement;
1417
import com.google.gson.JsonObject;
18+
import com.google.gson.JsonParser;
19+
20+
import lombok.Getter;
1521

1622
public class NameFetcher implements Callable<Map<UUID, String>> {
23+
1724
private static final String PROFILE_URL = "https://sessionserver.mojang.com/session/minecraft/profile/";
25+
26+
private static final HttpClient HTTP_CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
27+
28+
@Getter
1829
private final List<UUID> uuids;
1930

2031
public NameFetcher(List<UUID> uuids) {
@@ -24,25 +35,65 @@ public NameFetcher(List<UUID> uuids) {
2435
@Override
2536
public Map<UUID, String> call() throws Exception {
2637
Map<UUID, String> uuidStringMap = new HashMap<>();
38+
2739
for (UUID uuid : uuids) {
28-
HttpURLConnection connection = (HttpURLConnection) new URL(PROFILE_URL + uuid.toString().replace("-", ""))
29-
.openConnection();
30-
JsonObject response = (JsonObject) JsonParser
31-
.parseReader(new InputStreamReader(connection.getInputStream()));
32-
String name = response.get("name").getAsString();
33-
if (name == null) {
40+
HttpRequest request = HttpRequest.newBuilder()
41+
.uri(URI.create(PROFILE_URL + uuid.toString().replace("-", ""))).GET()
42+
.timeout(Duration.ofSeconds(5)).build();
43+
44+
HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
45+
46+
if (response.statusCode() == 204 || response.statusCode() == 404) {
47+
continue;
48+
}
49+
50+
if (response.statusCode() == 429) {
51+
System.out.println("VotingPlugin NameFetcher: Sent too many requests");
52+
continue;
53+
}
54+
55+
if (response.statusCode() < 200 || response.statusCode() >= 300) {
56+
throw new IOException("Failed to fetch name for uuid " + uuid + ", HTTP " + response.statusCode());
57+
}
58+
59+
JsonElement parsed = JsonParser.parseString(response.body());
60+
if (parsed == null || !parsed.isJsonObject()) {
3461
continue;
3562
}
36-
String cause = response.get("cause").getAsString();
37-
String errorMessage = response.get("errorMessage").getAsString();
63+
64+
JsonObject responseObject = parsed.getAsJsonObject();
65+
66+
String errorMessage = null;
67+
if (responseObject.has("errorMessage") && !responseObject.get("errorMessage").isJsonNull()) {
68+
errorMessage = responseObject.get("errorMessage").getAsString();
69+
}
70+
71+
String cause = null;
72+
if (responseObject.has("cause") && !responseObject.get("cause").isJsonNull()) {
73+
cause = responseObject.get("cause").getAsString();
74+
}
75+
3876
if (errorMessage != null && errorMessage.equals("TooManyRequestsException")) {
3977
System.out.println("VotingPlugin NameFetcher: Sent too many requests");
78+
continue;
79+
}
80+
81+
if (cause != null && !cause.isEmpty()) {
82+
throw new IllegalStateException(errorMessage != null ? errorMessage : cause);
83+
}
84+
85+
if (!responseObject.has("name") || responseObject.get("name").isJsonNull()) {
86+
continue;
4087
}
41-
if (cause != null && cause.length() > 0) {
42-
throw new IllegalStateException(errorMessage);
88+
89+
String name = responseObject.get("name").getAsString();
90+
if (name == null || name.isEmpty()) {
91+
continue;
4392
}
93+
4494
uuidStringMap.put(uuid, name);
4595
}
96+
4697
return uuidStringMap;
4798
}
4899
}

SimpleAPI/src/main/java/com/bencodez/simpleapi/player/PlayerUtils.java

Lines changed: 59 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
package com.bencodez.simpleapi.player;
22

3-
import java.io.BufferedReader;
4-
import java.io.InputStream;
5-
import java.io.InputStreamReader;
3+
import java.io.IOException;
64
import java.lang.reflect.InvocationTargetException;
75
import java.lang.reflect.Method;
8-
import java.net.HttpURLConnection;
9-
import java.net.URL;
6+
import java.net.URI;
7+
import java.net.http.HttpClient;
8+
import java.net.http.HttpRequest;
9+
import java.net.http.HttpResponse;
10+
import java.time.Duration;
11+
import java.util.UUID;
1012

1113
import org.bukkit.Bukkit;
1214
import org.bukkit.Location;
@@ -63,27 +65,34 @@ public static boolean canInteract(Player p, Block clickedBlock, Action action, I
6365
return true;
6466
}
6567

66-
public static java.util.UUID fetchUUID(String playerName) throws Exception {
67-
// Get response from Mojang API
68-
URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + playerName);
69-
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
70-
connection.connect();
68+
/**
69+
* Fetches UUID from Mojang API.
70+
*
71+
* @param playerName player name
72+
* @return UUID or null if not found
73+
* @throws Exception if request fails
74+
*/
75+
public static UUID fetchUUID(String playerName) throws Exception {
76+
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
7177

72-
if (connection.getResponseCode() == 400) {
73-
// plugin.debug("There is no player with the name \"" + playerName + "\"!");
78+
HttpRequest request = HttpRequest.newBuilder()
79+
.uri(URI.create("https://api.mojang.com/users/profiles/minecraft/" + playerName)).GET()
80+
.timeout(Duration.ofSeconds(5)).build();
81+
82+
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
83+
84+
if (response.statusCode() == 400 || response.statusCode() == 404) {
7485
return null;
7586
}
7687

77-
InputStream inputStream = connection.getInputStream();
78-
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
79-
80-
// Parse JSON response and get UUID
88+
if (response.statusCode() < 200 || response.statusCode() >= 300) {
89+
throw new IOException("HTTP " + response.statusCode());
90+
}
8191

82-
JsonElement element = JsonParser.parseReader(bufferedReader);
92+
JsonElement element = JsonParser.parseString(response.body());
8393
JsonObject object = element.getAsJsonObject();
8494
String uuidAsString = object.get("id").getAsString();
8595

86-
// Return UUID
8796
return parseUUIDFromString(uuidAsString);
8897
}
8998

@@ -185,37 +194,38 @@ public static IServerHandle loadHandle() {
185194
return serverHandle = new CraftBukkitHandle();
186195
}
187196
}
188-
189-
/**
190-
* Gets the nearest player to the given location within the specified max distance.
191-
*
192-
* @param location The center location to search from.
193-
* @param maxDistance The maximum distance (in blocks).
194-
* @return The nearest Player, or null if none are within range.
195-
*/
196-
public static Player getNearestPlayer(Location location, double maxDistance) {
197-
if (location == null || location.getWorld() == null) {
198-
return null;
199-
}
200-
201-
Player nearest = null;
202-
double maxDistanceSquared = maxDistance * maxDistance;
203-
double closestSoFar = maxDistanceSquared;
204-
205-
for (Player player : Bukkit.getOnlinePlayers()) {
206-
if (player.getWorld() != location.getWorld()) {
207-
continue;
208-
}
209-
210-
double distanceSquared = player.getLocation().distanceSquared(location);
211-
if (distanceSquared <= closestSoFar) {
212-
closestSoFar = distanceSquared;
213-
nearest = player;
214-
}
215-
}
216-
217-
return nearest;
218-
}
197+
198+
/**
199+
* Gets the nearest player to the given location within the specified max
200+
* distance.
201+
*
202+
* @param location The center location to search from.
203+
* @param maxDistance The maximum distance (in blocks).
204+
* @return The nearest Player, or null if none are within range.
205+
*/
206+
public static Player getNearestPlayer(Location location, double maxDistance) {
207+
if (location == null || location.getWorld() == null) {
208+
return null;
209+
}
210+
211+
Player nearest = null;
212+
double maxDistanceSquared = maxDistance * maxDistance;
213+
double closestSoFar = maxDistanceSquared;
214+
215+
for (Player player : Bukkit.getOnlinePlayers()) {
216+
if (player.getWorld() != location.getWorld()) {
217+
continue;
218+
}
219+
220+
double distanceSquared = player.getLocation().distanceSquared(location);
221+
if (distanceSquared <= closestSoFar) {
222+
closestSoFar = distanceSquared;
223+
nearest = player;
224+
}
225+
}
226+
227+
return nearest;
228+
}
219229

220230
private static java.util.UUID parseUUIDFromString(String uuidAsString) {
221231
String[] parts = { "0x" + uuidAsString.substring(0, 8), "0x" + uuidAsString.substring(8, 12),

0 commit comments

Comments
 (0)