List of usage examples for java.lang ClassLoader getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:de.decidr.test.database.factories.EntityFactory.java
/** * Returns the contents of a file that resides in "resources/" * /*w w w. j a v a 2 s . c o m*/ * @param fileName * file name without path * @return raw bytes of file */ public byte[] getFileBytes(String fileName) { if (!fileName.startsWith("/")) { fileName = "/" + fileName; } ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream inStream = loader.getResourceAsStream("files" + fileName); loader.getClass(); if (inStream == null) { throw new RuntimeException("Cannot open file " + fileName); } ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { IOUtils.copy(inStream, outStream); inStream.close(); } catch (IOException e) { throw new RuntimeException(e); } return outStream.toByteArray(); }
From source file:com.github.dozermapper.core.builder.xml.SchemaLSResourceResolver.java
/** * Attempt to resolve systemId resource from classpath by checking: * * 1. Try {@link SchemaLSResourceResolver#getClass()#getClassLoader()} * 2. Try {@link BeanContainer#getClassLoader()} * 3. Try {@link Activator#getBundle()}// w ww. ja v a 2s. c o m * * @param systemId systemId used by XSD * @return stream to XSD * @throws IOException if fails to find XSD */ private InputStream resolveFromClassPath(String systemId) throws IOException, URISyntaxException { InputStream source; String xsdPath; URI uri = new URI(systemId); if (uri.getScheme().equalsIgnoreCase("file")) { xsdPath = uri.toString(); } else { xsdPath = uri.getPath(); if (xsdPath.charAt(0) == '/') { xsdPath = xsdPath.substring(1); } } ClassLoader localClassLoader = getClass().getClassLoader(); LOG.debug("Trying to locate [{}] via ClassLoader [{}]", xsdPath, localClassLoader.getClass().getSimpleName()); //Attempt to find within this JAR URL url = localClassLoader.getResource(xsdPath); if (url == null) { //Attempt to find via user defined class loader DozerClassLoader dozerClassLoader = beanContainer.getClassLoader(); LOG.debug("Trying to locate [{}] via DozerClassLoader [{}]", xsdPath, dozerClassLoader.getClass().getSimpleName()); url = dozerClassLoader.loadResource(xsdPath); } if (url == null) { //Attempt to find via OSGi Bundle bundle = Activator.getBundle(); if (bundle != null) { LOG.debug("Trying to locate [{}] via Bundle [{}]", xsdPath, bundle.getClass().getSimpleName()); url = bundle.getResource(xsdPath); } } if (url == null) { throw new IOException("Could not resolve bean-mapping XML Schema [" + systemId + "]: not found in classpath; " + xsdPath); } try { source = url.openStream(); } catch (IOException ex) { throw new IOException("Could not resolve bean-mapping XML Schema [" + systemId + "]: not found in classpath; " + xsdPath, ex); } LOG.debug("Found bean-mapping XML Schema [{}] in classpath @ [{}]", systemId, url.toString()); return source; }
From source file:se.crisp.codekvast.support.web.config.WebjarVersionFilter.java
private void scanWebjars() { ClassLoader cl = WebjarVersionFilter.class.getClassLoader(); if (!(cl instanceof URLClassLoader)) { throw new UnsupportedOperationException( "Don't know how to scan classpath from " + cl.getClass().getName()); }/*from w w w. j a v a 2s .c o m*/ log.debug("Scanning classpath for webjars..."); URLClassLoader ucl = (URLClassLoader) cl; Pattern pattern = Pattern.compile(".*webjars/(.*?)/(.*?)/.*"); // For each URL in classpath for (URL url : ucl.getURLs()) { try { analyzeJar(url, pattern); } catch (IOException e) { log.warn("Cannot analyze " + url, e); } } log.debug("Found {} webjars", versions.size()); }
From source file:com.clican.pluto.orm.dynamic.impl.ClassLoaderUtilImpl.java
private void populateJars(Set<String> jars, ClassLoader loader) { if (!(loader instanceof URLClassLoader)) { if (log.isDebugEnabled()) { log.debug("The ClassLoader[" + loader.getClass().getName() + "] is ignored"); }/*from ww w .j a va 2 s.com*/ } else { URLClassLoader urlClassLoader = (URLClassLoader) loader; for (URL url : urlClassLoader.getURLs()) { jars.add(url.getPath()); } } if (loader == ClassLoader.getSystemClassLoader()) { return; } else { populateJars(jars, loader.getParent()); } }
From source file:io.vertx.lang.js.JSVerticleFactory.java
@Override public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception { init();/*from ww w .j a v a 2 s . co m*/ if (ENABLE_NODEJS_VERTICLES && IsolatingClassLoader.class.isAssignableFrom(classLoader.getClass()) && isNodeJS(classLoader)) return new NodeJSVerticle(VerticleFactory.removePrefix(verticleName), classLoader); return new JSVerticle(VerticleFactory.removePrefix(verticleName)); }
From source file:com.streamsets.datacollector.stagelibrary.ClassLoaderStageLibraryTask.java
private void resolveClassLoaderMethods(ClassLoader cl) { if (cl.getClass().getSimpleName().equals("SDCClassLoader")) { try {/*from ww w. j a va2s .c o m*/ duplicateClassLoaderMethod = cl.getClass().getMethod("duplicateStageClassLoader"); getClassLoaderKeyMethod = cl.getClass().getMethod("getName"); isPrivateClassLoaderMethod = cl.getClass().getMethod("isPrivate"); } catch (Exception ex) { throw new Error(ex); } } else { LOG.warn("No SDCClassLoaders available, there is no class isolation"); } }
From source file:jenkins.security.ClassFilterImpl.java
@SuppressWarnings("rawtypes") @Override// ww w. j av a2s . c o m public boolean isBlacklisted(Class _c) { for (CustomClassFilter f : ExtensionList.lookup(CustomClassFilter.class)) { Boolean r = f.permits(_c); if (r != null) { if (r) { LOGGER.log(Level.FINER, "{0} specifies a policy for {1}: {2}", new Object[] { f, _c.getName(), true }); } else { notifyRejected(_c, _c.getName(), String.format("%s specifies a policy for %s: %s ", f, _c.getName(), r)); } return !r; } } return cache.computeIfAbsent(_c, c -> { String name = c.getName(); if (Main.isUnitTest && (name.contains("$$EnhancerByMockitoWithCGLIB$$") || name.contains("$$FastClassByMockitoWithCGLIB$$") || name.startsWith("org.mockito."))) { mockOff(); return false; } if (ClassFilter.STANDARD.isBlacklisted(c)) { // currently never true, but may issue diagnostics notifyRejected(_c, _c.getName(), String.format("%s is not permitted ", _c.getName())); return true; } if (c.isArray()) { LOGGER.log(Level.FINE, "permitting {0} since it is an array", name); return false; } if (Throwable.class.isAssignableFrom(c)) { LOGGER.log(Level.FINE, "permitting {0} since it is a throwable", name); return false; } if (Enum.class.isAssignableFrom(c)) { // Class.isEnum seems to be false for, e.g., java.util.concurrent.TimeUnit$6 LOGGER.log(Level.FINE, "permitting {0} since it is an enum", name); return false; } String location = codeSource(c); if (location != null) { if (isLocationWhitelisted(location)) { LOGGER.log(Level.FINE, "permitting {0} due to its location in {1}", new Object[] { name, location }); return false; } } else { ClassLoader loader = c.getClassLoader(); if (loader != null && loader.getClass().getName().equals("hudson.remoting.RemoteClassLoader")) { LOGGER.log(Level.FINE, "permitting {0} since it was loaded by a remote class loader", name); return false; } } if (WHITELISTED_CLASSES.contains(name)) { LOGGER.log(Level.FINE, "tolerating {0} by whitelist", name); return false; } if (SUPPRESS_WHITELIST || SUPPRESS_ALL) { notifyRejected(_c, null, String.format( "%s in %s might be dangerous, so would normally be rejected; see https://jenkins.io/redirect/class-filter/", name, location != null ? location : "JRE")); return false; } notifyRejected(_c, null, String.format( "%s in %s might be dangerous, so rejecting; see https://jenkins.io/redirect/class-filter/", name, location != null ? location : "JRE")); return true; }); }
From source file:de.icongmbh.oss.maven.plugin.javassist.JavassistTransformerExecutor.java
private void debugClassLoader(final ClassPool classPool) { if (!LOGGER.isDebugEnabled()) { return;/*from www. ja v a 2 s . com*/ } LOGGER.debug(" - classPool: {}", classPool.toString()); ClassLoader classLoader = classPool.getClassLoader(); while (classLoader != null) { LOGGER.debug(" -- {}: {}", classLoader.getClass().getName(), classLoader.toString()); if (classLoader instanceof URLClassLoader) { LOGGER.debug(" --- urls: {}", Arrays.deepToString(((URLClassLoader) classLoader).getURLs())); } classLoader = classLoader.getParent(); } }
From source file:org.red5.server.winstone.WinstoneLoader.java
/** * Initialization./*from w ww . j a v a2 s . c o m*/ */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void init() { log.info("Loading Winstone context"); //get a reference to the current threads classloader final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); // root location for servlet container String serverRoot = System.getProperty("red5.root"); log.info("Server root: {}", serverRoot); String confRoot = System.getProperty("red5.config_root"); log.info("Config root: {}", confRoot); // configure the webapps folder, make sure we have one if (webappFolder == null) { // Use default webapps directory webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps"); } System.setProperty("red5.webapp.root", webappFolder); log.info("Application root: {}", webappFolder); // create one embedded (server) and use it everywhere Map args = new HashMap(); //args.put("webroot", webappFolder + "/root"); args.put("webappsDir", webappFolder); // Start server try { log.info("Starting Winstone servlet engine"); Launcher.initLogger(args); // spawns threads, so your application doesn't block embedded = new StoneLauncher(args); log.trace("Classloader for embedded: {} TCL: {}", Launcher.class.getClassLoader(), originalClassLoader); // get the default host HostConfiguration host = embedded.getHostGroup().getHostByName(null); // set the primary application loader LoaderBase.setApplicationLoader(new WinstoneApplicationLoader(host, applicationContext)); // get root first, we may want to start a spring config internally but for now skip it WebAppConfiguration root = host.getWebAppByURI("/"); log.trace("Root: {}", root); // scan the sub directories to determine our context names buildContextNameList(webappFolder); // loop the other contexts for (String contextName : contextNames) { WebAppConfiguration ctx = host.getWebAppByURI(contextName); // get access to the servlet context final ServletContext servletContext = ctx.getContext(contextName); log.debug("Context initialized: {}", servletContext.getContextPath()); //set the hosts id servletContext.setAttribute("red5.host.id", host.getHostname()); // get the path String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); try { final ClassLoader cldr = ctx.getLoader(); log.debug("Loader type: {}", cldr.getClass().getName()); // get the (spring) config file path final String contextConfigLocation = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null ? defaultSpringConfigLocation : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM); log.debug("Spring context config location: {}", contextConfigLocation); // get the (spring) parent context key final String parentContextKey = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null ? defaultParentContextKey : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM); log.debug("Spring parent context key: {}", parentContextKey); //set current threads classloader to the webapp classloader Thread.currentThread().setContextClassLoader(cldr); //create a thread to speed-up application loading Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) { public void run() { //set thread context classloader to web classloader Thread.currentThread().setContextClassLoader(cldr); //get the web app's parent context ApplicationContext parentContext = null; if (applicationContext.containsBean(parentContextKey)) { parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey); } else { log.warn("Parent context was not found: {}", parentContextKey); } // create a spring web application context final String contextClass = servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null ? XmlWebApplicationContext.class.getName() : servletContext.getInitParameter( org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM); //web app context (spring) ConfigurableWebApplicationContext appctx = null; try { Class<?> clazz = Class.forName(contextClass, true, cldr); appctx = (ConfigurableWebApplicationContext) clazz.newInstance(); } catch (Throwable e) { throw new RuntimeException("Failed to load webapplication context class.", e); } appctx.setConfigLocations(new String[] { contextConfigLocation }); appctx.setServletContext(servletContext); //set parent context or use current app context if (parentContext != null) { appctx.setParent(parentContext); } else { appctx.setParent(applicationContext); } // set the root webapp ctx attr on the each servlet context so spring can find it later servletContext.setAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx); //refresh the factory log.trace("Classloader prior to refresh: {}", appctx.getClassLoader()); appctx.refresh(); if (log.isDebugEnabled()) { log.debug("Red5 app is active: {} running: {}", appctx.isActive(), appctx.isRunning()); } } }; thread.setDaemon(true); thread.start(); } catch (Throwable t) { log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(), t.getMessage()); t.printStackTrace(); } finally { //reset the classloader Thread.currentThread().setContextClassLoader(originalClassLoader); } } } catch (Exception e) { if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) { log.error( "Error loading Winstone, unable to bind connector. You may not have permission to use the selected port", e); } else { log.error("Error loading Winstone", e); } } finally { registerJMX(); } }
From source file:org.jenkinsci.plugins.pipeline.maven.WithMavenStepExecution.java
private FilePath setupMavenSpy() throws IOException, InterruptedException { if (tempBinDir == null) { throw new IllegalStateException("tempBinDir not defined"); }//from www . j a v a 2 s.co m // 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<WithMavenStepExecution> clazz = WithMavenStepExecution.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; }