Resclone/src/main/java/io/gitlab/jfronny/resclone/fetchers/PackFetcher.java

59 lines
2.2 KiB
Java

package io.gitlab.jfronny.resclone.fetchers;
import com.google.gson.Gson;
import io.gitlab.jfronny.resclone.Resclone;
import io.gitlab.jfronny.resclone.data.RescloneException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Scanner;
public abstract class PackFetcher {
abstract public String getSourceTypeName(); // The name for users to specify in the config
abstract String getDownloadUrl(String baseUrl) throws RescloneException; // Return the actual download URL for the file based on the provided string
protected final Gson gson = Resclone.gson;
protected boolean urlValid(String url) {
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).toURI().toURL().openConnection();
connection.setRequestMethod("GET");
connection.connect();
return connection.getResponseCode() == 200;
}
catch (Throwable e) {
return false;
}
}
protected String readStringFromURL(String requestURL) throws IOException {
try (Scanner scanner = new Scanner(new URL(requestURL).openStream(), StandardCharsets.UTF_8.toString()))
{
scanner.useDelimiter("\\A");
return scanner.hasNext() ? scanner.next() : "";
}
}
public <T> T readJsonFromURL(String requestUrl, Class<T> classOfT) throws IOException {
return gson.fromJson(readStringFromURL(requestUrl), classOfT);
}
public void get(String baseUrl, Path targetPath) throws RescloneException {
String url = getDownloadUrl(baseUrl);
try (InputStream is = new URL(url).openStream()) {
FileOutputStream os = new FileOutputStream(targetPath.toFile());
byte[] dataBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(dataBuffer, 0, 1024)) != -1) {
os.write(dataBuffer, 0, bytesRead);
}
}
catch (Throwable e) {
throw new RescloneException("Could not download pack", e);
}
}
}