package io.gitlab.jfronny.resclone.fetchers; import io.gitlab.jfronny.resclone.Resclone; import io.gitlab.jfronny.resclone.util.Result; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; public abstract class PackFetcher { abstract public String getSourceTypeName(); // The name for users to specify in the config abstract String getDownloadUrl(String baseUrl) throws Exception; // Return the actual download URL for the file based on the provided string public Result get(String baseUrl, Path targetDir, boolean forceDownload) throws Exception { String url; try { url = getDownloadUrl(baseUrl); Resclone.urlCache.set(baseUrl, url); } catch (Exception e) { if (Resclone.urlCache.containsKey(baseUrl)) { e.printStackTrace(); url = Resclone.urlCache.get(baseUrl); } else { throw e; } } Path p = targetDir.resolve(Integer.toHexString(url.hashCode())); if (!forceDownload && Files.exists(p)) return new Result(p, false); Resclone.LOGGER.info("Downloading pack " + url); try (InputStream is = new URL(url).openStream()) { FileOutputStream os = new FileOutputStream(p.toFile()); byte[] dataBuffer = new byte[1024]; int bytesRead; while ((bytesRead = is.read(dataBuffer, 0, 1024)) != -1) { os.write(dataBuffer, 0, bytesRead); } Resclone.LOGGER.info("Completed download"); } catch (Throwable e) { throw new Exception("Could not download pack", e); } return new Result(p, true); } }