/**
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * Subscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portal.util;

import com.liferay.petra.reflect.ReflectionUtil;
import com.liferay.petra.string.StringBundler;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.Digester;
import com.liferay.portal.kernel.util.DigesterUtil;
import com.liferay.portal.kernel.util.StringUtil;

import java.io.File;
import java.io.InputStream;

import java.lang.reflect.Method;

import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

/**
 * @author Shuyang Zhou
 */
public class JarUtil {

	public static void downloadAndInstallJar(URL url, Path path)
		throws Exception {

		if (_log.isInfoEnabled()) {
			_log.info(StringBundler.concat("Downloading ", url, " to ", path));
		}

		try (InputStream inputStream = url.openStream()) {
			Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
		}

		if (_log.isInfoEnabled()) {
			_log.info(StringBundler.concat("Downloaded ", url, " to ", path));
		}
	}

	public static void downloadAndInstallJar(URL url, Path path, String sha1)
		throws Exception {

		if (_log.isInfoEnabled()) {
			_log.info(StringBundler.concat("Downloading ", url, " to ", path));
		}

		try (InputStream inputStream = url.openStream()) {
			Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
		}

		if (_log.isInfoEnabled()) {
			_log.info(StringBundler.concat("Downloaded ", url, " to ", path));
		}

		try (InputStream inputStream = Files.newInputStream(path)) {
			String digest = DigesterUtil.digestHex(Digester.SHA_1, inputStream);

			if (!StringUtil.equalsIgnoreCase(sha1, digest)) {
				throw new Exception(
					StringBundler.concat(
						"Unable to download ", url, " to ", path, " because ",
						sha1, " does not equal ", digest));
			}
		}
	}

	public static void downloadAndInstallJar(
			URL url, Path path, URLClassLoader urlClassLoader)
		throws Exception {

		downloadAndInstallJar(url, path);

		URI uri = path.toUri();

		if (_log.isInfoEnabled()) {
			_log.info(
				StringBundler.concat(
					"Installing ", path, " to ", urlClassLoader));
		}

		_addURLMethod.invoke(urlClassLoader, uri.toURL());

		if (_log.isInfoEnabled()) {
			_log.info(
				StringBundler.concat(
					"Installed ", path, " to ", urlClassLoader));
		}
	}

	public static void downloadAndInstallJar(
			URL url, Path path, URLClassLoader urlClassLoader, String sha1)
		throws Exception {

		downloadAndInstallJar(url, path, sha1);

		URI uri = path.toUri();

		if (_log.isInfoEnabled()) {
			_log.info(
				StringBundler.concat(
					"Installing ", path, " to ", urlClassLoader));
		}

		_addURLMethod.invoke(urlClassLoader, uri.toURL());

		if (_log.isInfoEnabled()) {
			_log.info(
				StringBundler.concat(
					"Installed ", path, " to ", urlClassLoader));
		}
	}

	/**
	 * @deprecated As of Athanasius (7.3.x), replaced by {@link
	 #downloadAndInstallJar(URL, Path)}
	 */
	@Deprecated
	public static Path downloadAndInstallJar(
			URL url, String libPath, String name)
		throws Exception {

		File file = new File(libPath, name);

		Path path = file.toPath();

		downloadAndInstallJar(url, path);

		return path;
	}

	/**
	 * @deprecated As of Athanasius (7.3.x), replaced by {@link
	 #downloadAndInstallJar(URL, Path, URLClassLoader)}
	 */
	@Deprecated
	public static void downloadAndInstallJar(
			URL url, String libPath, String name, URLClassLoader urlClassLoader)
		throws Exception {

		File file = new File(libPath, name);

		Path path = file.toPath();

		downloadAndInstallJar(url, path, urlClassLoader, null);
	}

	private static final Log _log = LogFactoryUtil.getLog(JarUtil.class);

	private static final Method _addURLMethod;

	static {
		try {
			_addURLMethod = ReflectionUtil.getDeclaredMethod(
				URLClassLoader.class, "addURL", URL.class);
		}
		catch (Exception exception) {
			throw new ExceptionInInitializerError(exception);
		}
	}

}