com.arextest.common.utils.RemoteJarLoaderUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of arex-common Show documentation
Show all versions of arex-common Show documentation
arex-common is a Java common library.
package com.arextest.common.utils;
import com.arextest.common.model.classloader.RemoteJarClassLoader;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;
@Slf4j
public class RemoteJarLoaderUtils {
public static RemoteJarClassLoader loadJar(String jarUrl) throws MalformedURLException {
URL resource;
if (jarUrl.startsWith("http")) {
resource = new URL(jarUrl);
} else {
resource = RemoteJarLoaderUtils.class.getClassLoader().getResource(jarUrl);
}
if (resource == null) {
resource = new File(jarUrl).toURI().toURL();
}
try {
URLConnection urlConnection = resource.openConnection();
urlConnection.getInputStream().close();
} catch (IOException e) {
LOGGER.error("Failed to load jar: {}", jarUrl, e);
throw new RuntimeException("Failed to load jar: " + jarUrl, e);
}
return new RemoteJarClassLoader(new URL[]{resource}, RemoteJarLoaderUtils.class.getClassLoader());
}
public static List loadService(Class clazz, SecureClassLoader classLoader) {
ServiceLoader serviceLoader = ServiceLoader.load(clazz, classLoader);
List res = new ArrayList<>();
Iterator iterator = serviceLoader.iterator();
while (iterator.hasNext()) {
res.add(iterator.next());
}
return res;
}
}