Java Code Examples for java.security.CodeSource#getLocation()

The following examples show how to use java.security.CodeSource#getLocation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PathManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 2
Source File: SwaggerHammer.java    From spark-swagger with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: BundleVersionUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: ClassUtils.java    From sofa-ark with Apache License 2.0 6 votes vote down vote up
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();
    }
 
Example 5
Source File: JarUtil.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source File: ClassUtils.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 得到类所在地址,可以是文件,也可以是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);

}
 
Example 7
Source File: ClassPathUtils.java    From confucius-commons with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 8
Source File: ClassLoader.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private String defineClassSourceLocation(ProtectionDomain pd)
{
    CodeSource cs = pd.getCodeSource();
    String source = null;
    if (cs != null && cs.getLocation() != null) {
        source = cs.getLocation().toString();
    }
    return source;
}
 
Example 9
Source File: ClassUtils.java    From arthas with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 10
Source File: Plug.java    From apdu4j with MIT License 5 votes vote down vote up
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();
}
 
Example 11
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
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;
}
 
Example 12
Source File: ClassLoader.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private String defineClassSourceLocation(ProtectionDomain pd)
{
    CodeSource cs = pd.getCodeSource();
    String source = null;
    if (cs != null && cs.getLocation() != null) {
        source = cs.getLocation().toString();
    }
    return source;
}
 
Example 13
Source File: JdbcBridge.java    From clickhouse-jdbc-bridge with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: LintDetectorTest.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 15
Source File: MCRServletContainerInitializer.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
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();
}
 
Example 16
Source File: AbstractDetectorTest.java    From Android-Lint-Checks with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 17
Source File: BaseTestCase.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 18
Source File: JarUtil.java    From opentest with MIT License 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 19
Source File: AnalyzedWorld.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    CodeSource codeSource = codeSource();
    if (codeSource == null) {
        return className();
    } else {
        return className() + " (" + codeSource.getLocation() + ")";
    }
}
 
Example 20
Source File: ExtendedAnnotationTest.java    From annotation-tools with MIT License 5 votes vote down vote up
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";
}