下面列出了java.security.CodeSource# getLocation ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Nullable
public static String getJarPathForClass(@Nonnull Class aClass) {
String path = "/" + aClass.getName().replace('.', '/') + ".class";
try {
CodeSource codeSource = aClass.getProtectionDomain().getCodeSource();
if (codeSource != null) {
URL location = codeSource.getLocation();
if (location != null) {
URI uri = location.toURI();
return extractRoot(uri.toURL(), path);
}
}
}
catch (URISyntaxException | MalformedURLException e) {
throw new RuntimeException(e);
}
String resourceRoot = getResourceRoot(aClass, path);
return resourceRoot != null ? new File(resourceRoot).getAbsolutePath() : null;
}
/**
* Get Class Location URL from specified {@link Class} at runtime
*
* @param type
* {@link Class}
* @return If <code>type</code> is <code>{@link Class#isPrimitive() primitive type}</code>, <code>{@link
* Class#isArray() array type}</code>, <code>{@link Class#isSynthetic() synthetic type}</code> or {a security
* manager exists and its <code>checkPermission</code> method doesn't allow getting the ProtectionDomain., return
* <code>null</code>
*/
public static URL getRuntimeClassLocation(Class<?> type) {
ClassLoader classLoader = type.getClassLoader();
URL location = null;
if (classLoader != null) { // Non-Bootstrap
try {
ProtectionDomain protectionDomain = type.getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
location = codeSource == null ? null : codeSource.getLocation();
} catch (SecurityException exception) {
}
} else if (!type.isPrimitive() && !type.isArray() && !type.isSynthetic()) { // Bootstrap ClassLoader
// Class was loaded by Bootstrap ClassLoader
location = ClassLoaderUtils.getClassResource(ClassLoader.getSystemClassLoader(), type.getName());
}
return location;
}
/**
* 得到类所在地址,可以是文件,也可以是jar包
*
* @return the code base
*/
public String getCodeBase() {
if (codebase == null) {
synchronized (this) {
if (codebase == null) {
String file = null;
ProtectionDomain domain = type.getProtectionDomain();
if (domain != null) {
CodeSource source = domain.getCodeSource();
if (source != null) {
URL location = source.getLocation();
if (location != null) {
file = location.getFile();
}
}
}
codebase = Optional.ofNullable(file);
}
}
}
return codebase.orElse(null);
}
/**
* Returns list of resources that were found in staticResourcesFolder
*
* @param staticResourcesFolder - resource folder
* @return - absolute path to resources within staticResourcesFolder
*/
private static ArrayList<String> find(String staticResourcesFolder) throws Exception {
if (!staticResourcesFolder.endsWith("/")) {
staticResourcesFolder = staticResourcesFolder + "/";
}
CodeSource src = JarUtil.class.getProtectionDomain().getCodeSource();
ArrayList<String> staticResources = new ArrayList<>();
if (src != null) {
URL jar = src.getLocation();
try (ZipInputStream zip = new ZipInputStream(jar.openStream())) {
ZipEntry ze;
while ((ze = zip.getNextEntry()) != null) {
String entryName = ze.getName();
if (!ze.isDirectory() && entryName.startsWith(staticResourcesFolder)) {
staticResources.add(entryName);
}
}
}
}
return staticResources;
}
public static String getCodeBase(Class<?> cls) {
if (cls == null) {
return null;
}
ProtectionDomain domain = cls.getProtectionDomain();
if (domain == null) {
return null;
}
CodeSource source = domain.getCodeSource();
if (source == null) {
return null;
}
URL location = source.getLocation();
if (location == null) {
return null;
}
return location.getFile();
}
public static String getBundleVersion( String bundleName )
{
Bundle bundle = Platform.getBundle( bundleName );
if ( bundle != null )
{
return bundle.getVersion( ).toString( );
}
// the engine.jar are in the class path
ProtectionDomain domain = BundleVersionUtil.class.getProtectionDomain( );
if ( domain != null )
{
CodeSource codeSource = domain.getCodeSource( );
if ( codeSource != null )
{
URL jarUrl = codeSource.getLocation( );
if( jarUrl != null )
{
return jarUrl.getFile( );
}
}
}
return UNKNOWN_VERSION;
}
private List<String> listFiles(String prefix) throws IOException {
List<String> uiFiles = new ArrayList<>();
CodeSource src = SparkSwagger.class.getProtectionDomain().getCodeSource();
if (src != null) {
URL jar = src.getLocation();
ZipInputStream zip = new ZipInputStream(jar.openStream());
while (true) {
ZipEntry e = zip.getNextEntry();
if (e == null)
break;
String name = e.getName();
if (name.startsWith(prefix)) {
uiFiles.add(name);
}
}
}
return uiFiles;
}
public String nameExpected(String className) {
Class cls = this.getClass();
ProtectionDomain pr = cls.getProtectionDomain();
CodeSource cs = pr.getCodeSource();
URL loc = cs.getLocation();
String s = loc.toString();
if(s.startsWith("file:")) {
s = s.substring(5);
}
// in the default asmx ant script, class will be run from something like
// asmx/output/... so just cut things off at asmx
s = s.substring(0, s.lastIndexOf("asmx")+4);
return s+"/test/conform/cases/"+className+".expected";
}
@Override
public String toString() {
CodeSource codeSource = codeSource();
if (codeSource == null) {
return className();
} else {
return className() + " (" + codeSource.getLocation() + ")";
}
}
/**
* Locates the folder where the unit test java source file is saved.
*
* @return the path name where the test java source file locates.
*/
protected String getClassFolder( )
{
String pathBase = null;
ProtectionDomain domain = this.getClass( ).getProtectionDomain( );
if ( domain != null )
{
CodeSource source = domain.getCodeSource( );
if ( source != null )
{
URL url = source.getLocation( );
pathBase = url.getPath( );
if ( pathBase.endsWith( "bin/" ) ) //$NON-NLS-1$
pathBase = pathBase.substring( 0, pathBase.length( ) - 4 );
if ( pathBase.endsWith( "bin" ) ) //$NON-NLS-1$
pathBase = pathBase.substring( 0, pathBase.length( ) - 3 );
}
}
pathBase = pathBase + TEST_FOLDER;
String className = this.getClass( ).getName( );
int lastDotIndex = className.lastIndexOf( "." ); //$NON-NLS-1$
className = className.substring( 0, lastDotIndex );
className = pathBase + className.replace( '.', '/' );
return className;
}
private FilePath setupMavenSpy() throws IOException, InterruptedException {
if (tempBinDir == null) {
throw new IllegalStateException("tempBinDir not defined");
}
// Mostly for testing / debugging in the IDE
final String MAVEN_SPY_JAR_URL = "org.jenkinsci.plugins.pipeline.maven.mavenSpyJarUrl";
String mavenSpyJarUrl = System.getProperty(MAVEN_SPY_JAR_URL);
InputStream in;
if (mavenSpyJarUrl == null) {
String embeddedMavenSpyJarPath = "META-INF/lib/pipeline-maven-spy.jar";
LOGGER.log(Level.FINE, "Load embedded maven spy jar '" + embeddedMavenSpyJarPath + "'");
// Don't use Thread.currentThread().getContextClassLoader() as it doesn't show the resources of the plugin
Class<WithMavenStepExecution2> clazz = WithMavenStepExecution2.class;
ClassLoader classLoader = clazz.getClassLoader();
LOGGER.log(Level.FINE, "Load " + embeddedMavenSpyJarPath + " using classloader " + classLoader.getClass() + ": " + classLoader);
in = classLoader.getResourceAsStream(embeddedMavenSpyJarPath);
if (in == null) {
CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
String msg = "Embedded maven spy jar not found at " + embeddedMavenSpyJarPath + " in the pipeline-maven-plugin classpath. " +
"Maven Spy Jar URL can be defined with the system property: '" + MAVEN_SPY_JAR_URL + "'" +
"Classloader " + classLoader.getClass() + ": " + classLoader + ". " +
"Class " + clazz.getName() + " loaded from " + (codeSource == null ? "#unknown#" : codeSource.getLocation());
throw new IllegalStateException(msg);
}
} else {
LOGGER.log(Level.FINE, "Load maven spy jar provided by system property '" + MAVEN_SPY_JAR_URL + "': " + mavenSpyJarUrl);
in = new URL(mavenSpyJarUrl).openStream();
}
FilePath mavenSpyJarFilePath = tempBinDir.child("pipeline-maven-spy.jar");
mavenSpyJarFilePath.copyFrom(in);
return mavenSpyJarFilePath;
}
private String defineClassSourceLocation(ProtectionDomain pd)
{
CodeSource cs = pd.getCodeSource();
String source = null;
if (cs != null && cs.getLocation() != null) {
source = cs.getLocation().toString();
}
return source;
}
public static String getCodeSource(final CodeSource cs) {
if (null == cs || null == cs.getLocation() || null == cs.getLocation().getFile()) {
return com.taobao.arthas.core.util.Constants.EMPTY_STRING;
}
return cs.getLocation().getFile();
}
static String pluginfile(Object c) {
CodeSource src = c.getClass().getProtectionDomain().getCodeSource();
if (src == null)
return "BUILTIN";
URL l = src.getLocation();
if (l.getProtocol().equals("file")) {
return l.getFile();
}
return l.toExternalForm();
}
private String defineClassSourceLocation(ProtectionDomain pd)
{
CodeSource cs = pd.getCodeSource();
String source = null;
if (cs != null && cs.getLocation() != null) {
source = cs.getLocation().toString();
}
return source;
}
private static Arguments parseArguments(String... argv) {
Arguments args = new Arguments();
try {
final JCommander build = JCommander.newBuilder()
.addObject(args)
.build();
build.parse(argv);
if (args.isHelp()) {
// try to create full path to binary in help
CodeSource src = JdbcBridge.class.getProtectionDomain().getCodeSource();
if (src != null && src.getLocation().toString().endsWith(".jar")) {
URL jar = src.getLocation();
String jvmPath = System.getProperties().getProperty("java.home") + File.separator + "bin" + File.separator + "java";
build.setProgramName(jvmPath + " -jar " + jar.getPath());
build.setColumnSize(200);
}
build.usage();
System.exit(0);
}
} catch (Exception err) {
log.error("Error parsing incoming config: " + err.getMessage());
System.exit(1);
}
return args;
}
/**
* Returns the Android source tree root dir.
* @return the root dir or null if it couldn't be computed.
*/
protected File getRootDir() {
CodeSource source = getClass().getProtectionDomain().getCodeSource();
if (source != null) {
URL location = source.getLocation();
try {
File dir = SdkUtils.urlToFile(location);
assertTrue(dir.getPath(), dir.exists());
while (dir != null) {
File settingsGradle = new File(dir, "settings.gradle"); //$NON-NLS-1$
if (settingsGradle.exists()) {
return dir.getParentFile().getParentFile();
}
File lint = new File(dir, "lint"); //$NON-NLS-1$
if (lint.exists() && new File(lint, "cli").exists()) { //$NON-NLS-1$
return dir.getParentFile().getParentFile();
}
dir = dir.getParentFile();
}
return null;
} catch (MalformedURLException e) {
fail(e.getLocalizedMessage());
}
}
return null;
}
private static String getSource(final Class<? extends MCRServletContainerInitializer> clazz) {
if (clazz == null) {
return null;
}
ProtectionDomain protectionDomain = clazz.getProtectionDomain();
CodeSource codeSource = protectionDomain.getCodeSource();
if (codeSource == null) {
LogManager.getLogger().warn("Cannot get CodeSource.");
return null;
}
URL location = codeSource.getLocation();
String fileName = location.getFile();
File sourceFile = new File(fileName);
return sourceFile.getName();
}
private File getTestDataRootDir() {
CodeSource source = getClass().getProtectionDomain().getCodeSource();
if (source != null) {
URL location = source.getLocation();
try {
File classesDir = SdkUtils.urlToFile(location);
return classesDir.getParentFile().getAbsoluteFile().getParentFile().getParentFile();
} catch (MalformedURLException e) {
fail(e.getLocalizedMessage());
}
}
return null;
}
/**
* Returns the JarFile instance corresponding to the JAR containing the
* specified class.
*/
public static JarFile getJarFile(Class klass) {
try {
CodeSource src = klass.getProtectionDomain().getCodeSource();
if (src != null) {
URL jarUrl = src.getLocation();
return new JarFile(new File(jarUrl.getPath()));
} else {
return null;
}
} catch (IOException ex1) {
return null;
}
}