anvillib/common/src/main/java/net/anvilcraft/anvillib/cosmetics/remote/thread/AbstractFileDownloaderThread.java

85 lines
2.8 KiB
Java
Raw Normal View History

2023-11-19 15:44:13 +01:00
package net.anvilcraft.anvillib.cosmetics.remote.thread;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import net.anvilcraft.anvillib.AnvilLib;
2023-11-24 21:20:58 +01:00
public abstract class AbstractFileDownloaderThread implements Runnable {
2023-11-19 15:44:13 +01:00
protected Gson gson = new GsonBuilder().create();
protected HttpClient client = HttpClient.newBuilder().build();
protected final String version;
2023-11-24 21:20:58 +01:00
public AbstractFileDownloaderThread(String version) {
2023-11-19 15:44:13 +01:00
this.version = version;
}
protected HttpRequest buildRequest(URI url) {
return HttpRequest.newBuilder()
.GET()
.uri(url)
.header("User-Agent", System.getProperty("java.version"))
.header("X-AnvilLib-Version", this.version)
.header("X-Minecraft-Version", "1.18.2")
.build();
}
public InputStream getStreamForURL(URI url) {
HttpRequest req = this.buildRequest(url);
InputStream is = null;
try {
2023-11-24 18:52:05 +01:00
HttpResponse<InputStream> res
= client.send(req, HttpResponse.BodyHandlers.ofInputStream());
2023-11-19 15:44:13 +01:00
if (res.statusCode() == 200) {
2023-11-24 18:52:05 +01:00
is = res.body();
2023-11-19 15:44:13 +01:00
} else if (res.statusCode() != 404) {
AnvilLib.LOGGER.error("Unexpected status code: {}", res.statusCode());
}
} catch (IOException | InterruptedException e) {
AnvilLib.LOGGER.error(e);
}
return is;
}
public String getStringForURL(URI url) {
HttpRequest req = this.buildRequest(url);
String is = null;
try {
2023-11-24 18:52:05 +01:00
HttpResponse<String> res
= client.send(req, HttpResponse.BodyHandlers.ofString());
2023-11-19 15:44:13 +01:00
if (res.statusCode() == 200) {
2023-11-24 18:52:05 +01:00
is = res.body();
2023-11-19 15:44:13 +01:00
} else if (res.statusCode() != 404) {
AnvilLib.LOGGER.error("Unexpected status code: {}", res.statusCode());
}
} catch (IOException | InterruptedException e) {
AnvilLib.LOGGER.error(e);
}
return is;
}
public <T> T loadJson(URI url, Class<T> type) throws IOException {
InputStream stream = this.getStreamForURL(url);
2023-11-24 18:52:05 +01:00
if (stream == null)
return null;
2023-11-19 15:44:13 +01:00
try {
T json = this.gson.fromJson(new InputStreamReader(stream), type);
return json;
2023-11-24 18:52:05 +01:00
} catch (JsonSyntaxException | JsonIOException e) {
2023-11-19 15:44:13 +01:00
throw new IOException(e);
} finally {
stream.close();
}
}
}