Newer
Older
ultramine_bootstrap / src / main / java / org / ultramine / bootstrap / maven / MavenDownloadable.java
@vlad20012 vlad20012 on 31 Jul 2017 2 KB Initial commit
package org.ultramine.bootstrap.maven;

import org.apache.commons.io.FileUtils;
import org.ultramine.bootstrap.deps.IRepository;
import org.ultramine.bootstrap.deps.AbstractDownloadable;
import org.ultramine.bootstrap.exceptions.ApplicationErrorException;
import org.ultramine.bootstrap.util.HashUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;

public class MavenDownloadable extends AbstractDownloadable
{
	private final List<IRepository> repositories;
	private final MavenDependency dependency;

	public MavenDownloadable(List<IRepository> repositories, MavenDependency dependency)
	{
		this.repositories = repositories;
		this.dependency = dependency;
	}

	@Override
	public void download() throws IOException
	{
		String artifactName = dependency.getArtifactFilename();
		File output = new File(outputDir, artifactName);
		File checkSumFile = new File(checkSumsDir, artifactName+".sha1");
		if(output.isFile() && checkSumFile.isFile())
		{
			if(HashUtil.sha1Str(output).equals(FileUtils.readFileToString(checkSumFile)))
				return;
		}
		ensureFileWritable(output);
		ensureFileWritable(checkSumFile);
		String path = dependency.getArtifactPath();
		for(IRepository repo : repositories)
			if(tryDownload(output, checkSumFile, path, repo))
				return;
		throw new FileNotFoundException("Maven dependency not found in any repositories: "+dependency);
	}

	private boolean tryDownload(File output, File checkSumFile, String path, IRepository repo) throws IOException
	{
		try
		{
			InputStream resolved = repo.resolve(path);
			if(resolved == null)
				return false;
			System.out.println("Downloading " + dependency.getArtifactName() + " from " + repo + "/" + path);
			String computedCheckSum = copyAndDigest(resolved, new FileOutputStream(output));
			String loadedCheckSum = repo.resolveCheckSum(path);
			if(loadedCheckSum != null && !loadedCheckSum.equals(computedCheckSum))
				throw new RuntimeException("CheckSums failed for " + dependency + "("+computedCheckSum + " != " + loadedCheckSum + ")");
			FileUtils.writeStringToFile(checkSumFile, computedCheckSum);
			return true;
		} catch (UnknownHostException e)
		{
			throw new ApplicationErrorException(e, "error.unavailable.host", e.getMessage());
		} catch (SocketTimeoutException | ConnectException e)
		{
			throw new ApplicationErrorException(e, "error.unavailable.maven", repo.toString());
		}
	}

	@Override
	public String toString()
	{
		return dependency.toString();
	}
}