private static void showThreads(PrintStream pw, ThreadGroup g, Thread current) { int nthreads = g.activeCount(); pw.println("\nThread Group = " + g.getName() + " activeCount= " + nthreads); Thread[] tarray = new Thread[nthreads]; int n = g.enumerate(tarray, false); for (int i = 0; i < n; i++) { Thread thread = tarray[i]; ClassLoader loader = thread.getContextClassLoader(); String loaderName = (loader == null) ? "Default" : loader.getClass().getName(); Thread.State state = thread.getState(); long id = thread.getId(); pw.print(" " + id + " " + thread.getName() + " " + state + " " + loaderName); if (thread == current) pw.println(" **** CURRENT ***"); else pw.println(); } int ngroups = g.activeGroupCount(); ThreadGroup[] garray = new ThreadGroup[ngroups]; int ng = g.enumerate(garray, false); for (int i = 0; i < ng; i++) { ThreadGroup nested = garray[i]; showThreads(pw, nested, current); } }
static { Attributes m = null; final URL loc = Prop.LOCATION; if (loc != null) { final String jar = loc.getFile(); try { final ClassLoader cl = JarManifest.class.getClassLoader(); final Enumeration<URL> list = cl.getResources("META-INF/MANIFEST.MF"); while (list.hasMoreElements()) { final URL url = list.nextElement(); if (!url.getFile().contains(jar)) continue; final InputStream in = url.openStream(); try { m = new Manifest(in).getMainAttributes(); break; } finally { in.close(); } } } catch (final IOException ex) { Util.errln(ex); } } MAP = m; }
/** * Replacement for <code>Class.forName()</code> that also returns Class instances for primitives * (like "int") and array class names (like "String[]"). * * @param name the name of the Class * @param classLoader the class loader to use (may be <code>null</code>, which indicates the * default class loader) * @return Class instance for the supplied name * @throws ClassNotFoundException if the class was not found * @throws LinkageError if the class file could not be loaded * @see Class#forName(String, boolean, ClassLoader) */ public static Class<?> forName(String name, ClassLoader classLoader) throws ClassNotFoundException, LinkageError { Class<?> clazz = resolvePrimitiveClassName(name); if (clazz != null) { return clazz; } // "java.lang.String[]" style arrays if (name.endsWith(ARRAY_SUFFIX)) { String elementClassName = name.substring(0, name.length() - ARRAY_SUFFIX.length()); Class<?> elementClass = forName(elementClassName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } // "[Ljava.lang.String;" style arrays int internalArrayMarker = name.indexOf(INTERNAL_ARRAY_PREFIX); if (internalArrayMarker != -1 && name.endsWith(";")) { String elementClassName = null; if (internalArrayMarker == 0) { elementClassName = name.substring(INTERNAL_ARRAY_PREFIX.length(), name.length() - 1); } else if (name.startsWith("[")) { elementClassName = name.substring(1); } Class<?> elementClass = forName(elementClassName, classLoader); return Array.newInstance(elementClass, 0).getClass(); } ClassLoader classLoaderToUse = classLoader; if (classLoaderToUse == null) { classLoaderToUse = getClassLoader(); } return classLoaderToUse.loadClass(name); }
/** * Given an provider interface name register instance classes. The class path is searched for * service provider lists as described by the JAR File specification for service providers * * @param interfaceName name of the implemented interface. * @return boolean true if at least one instance class could be registered with this factory. */ protected boolean registerProviders(String interfaceName) { ClassLoader loader = getClass().getClassLoader(); boolean registeredSomething = false; try { Enumeration<URL> providerLists = loader.getResources("META-INF/services/" + interfaceName); while (providerLists.hasMoreElements()) { try { URI providerList = providerLists.nextElement().toURI(); registeredSomething |= registerFromFile(providerList); } catch (URISyntaxException badURI) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Failed to convert service URI", badURI); } } } } catch (IOException ex) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Failed to locate provider lists", ex); } } return registeredSomething; }
/** Copy one predefined Template from resources to a file. */ static void migrateTemplate(String template) throws IOException { File dir = TemplateDatabase.TemplateDir; File file = new File(dir, template); ClassLoader loader = TemplateDeployer.class.getClassLoader(); InputStream in = loader.getResourceAsStream("com/lightcrafts/templates/resources/" + template); if (in == null) { throw new IOException("Couldn't find resource for template " + template); } OutputStream out = new FileOutputStream(file); byte[] buffer = new byte[10000]; // bigger than any template try { int count; do { count = in.read(buffer); if (count > 0) { out.write(buffer, 0, count); } } while (count >= 0); } finally { try { out.close(); } catch (IOException e) { System.out.println("Failed to close template " + template); } } }
public String readFileFromJAR(String filepath) { String out = ""; try { // setup input buffer ClassLoader cl = this.getClass().getClassLoader(); InputStream instream = cl.getResourceAsStream(filepath); BufferedReader filereader = new BufferedReader(new InputStreamReader(instream)); // read lines String line = filereader.readLine(); while (line != null) { out += "\n" + line; line = filereader.readLine(); } filereader.close(); } catch (Exception e) { // e.printStackTrace(); } return out; }
/** * Executes a query. * * @param query query to be executed * @return list of serialized result items * @throws IOException error during query execution */ private StringList execute(final WebDAVQuery query) throws IOException { final ClassLoader cl = getClass().getClassLoader(); final InputStream s = cl.getResourceAsStream(FILE); if (s == null) throw new IOException("WebDAV module not found"); final byte[] module = new IOStream(s).read(); final QueryProcessor qp = new QueryProcessor(query.toString(), http.context()); try { for (final Entry<String, Object> entry : query.entries()) { qp.bind(entry.getKey(), entry.getValue()); } qp.ctx.parseLibrary(string(module), FILE, qp.sc); final Result r = qp.execute(); final int n = (int) r.size(); final StringList items = new StringList(n); for (int i = 0; i < n; i++) { final ArrayOutput ao = new ArrayOutput(); r.serialize(Serializer.get(ao), 0); items.add(ao.toString()); } return items; } catch (final QueryException ex) { throw new BaseXException(ex); } catch (final Exception ex) { Util.debug(ex); throw new BaseXException(ex); } finally { qp.close(); } }
/** * Load from resource. url = ZeppelinConfiguration.class.getResource(ZEPPELIN_SITE_XML); * * @throws ConfigurationException */ public static ZeppelinConfiguration create() { if (conf != null) { return conf; } ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL url; url = ZeppelinConfiguration.class.getResource(ZEPPELIN_SITE_XML); if (url == null) { ClassLoader cl = ZeppelinConfiguration.class.getClassLoader(); if (cl != null) { url = cl.getResource(ZEPPELIN_SITE_XML); } } if (url == null) { url = classLoader.getResource(ZEPPELIN_SITE_XML); } if (url == null) { LOG.warn("Failed to load configuration, proceeding with a default"); conf = new ZeppelinConfiguration(); } else { try { LOG.info("Load configuration from " + url); conf = new ZeppelinConfiguration(url); } catch (ConfigurationException e) { LOG.warn("Failed to load configuration from " + url + " proceeding with a default", e); conf = new ZeppelinConfiguration(); } } return conf; }
@Override protected synchronized Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException { Class<?> c = null; try { try { ClassLoader cl = getParent(); c = cl.loadClass(className); if (c != null) return c; } catch (ClassNotFoundException e) { /* let the next one handle this */ } try { c = findJarClass(className); if (c != null) return c; } catch (Exception e) { System.out.println( "Error loading class [" + className + "] from jars in war file [" + outerFile.getName() + "]: " + e.toString()); e.printStackTrace(); } throw new ClassNotFoundException("Class [" + className + "] not found"); } finally { if (c != null && resolve) { resolveClass(c); } } }
/** @param frameName title name for frame */ public ShowSavedResults(String frameName) { super(frameName); aboutRes = new JTextArea( "Select a result set from" + "\nthose listed and details" + "\nof that analysis will be" + "\nshown here. Then you can" + "\neither delete or view those" + "\nresults using the buttons below."); aboutScroll = new JScrollPane(aboutRes); ss = new JScrollPane(sp); ss.getViewport().setBackground(Color.white); // resMenu.setLayout(new FlowLayout(FlowLayout.LEFT,10,1)); ClassLoader cl = getClass().getClassLoader(); rfii = new ImageIcon(cl.getResource("images/Refresh_button.gif")); // results status resButtonStatus = new JPanel(new BorderLayout()); Border loweredbevel = BorderFactory.createLoweredBevelBorder(); Border raisedbevel = BorderFactory.createRaisedBevelBorder(); Border compound = BorderFactory.createCompoundBorder(raisedbevel, loweredbevel); statusField = new JTextField(); statusField.setBorder(compound); statusField.setEditable(false); }
@Test public void testResourceLookupWithPrefixAfterLoading() throws Exception { assertThat(classLoader.loadClass(Foo.class.getName()).getClassLoader(), is(classLoader)); assertThat( classLoader.getResource("/" + Foo.class.getName().replace('.', '/') + CLASS_FILE), expectedResourceLookup ? notNullValue(URL.class) : nullValue(URL.class)); }
private ClassLoader getRootLoader() { ClassLoader ret; for (ret = this.getClass().getClassLoader(); ret != null && ret.getParent() != null; ret = ret.getParent()) {} return ret; }
public <T> List<Class<T>> getInterfaceImplementations(Class<T> interfaceClass, File f) throws IOException, ClassNotFoundException { ArrayList<Class<T>> list = new ArrayList<>(); List<String> classes = null; if (f.isDirectory()) { classes = getClassesFromDir(f); } else { classes = getClassesFromJar(f); } URL url = f.toURI().toURL(); ClassLoader cl = new URLClassLoader(new URL[] {url}, this.getClass().getClassLoader()); for (String klazz : classes) { try { Class<?> c = cl.loadClass(klazz); if (interfaceClass.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())) { list.add((Class<T>) c); } } catch (Throwable t) { LOGGER.warn( String.format( "Error checking if class %s from file %s is implementing %s: %s", klazz, f, interfaceClass.getName(), t.getMessage())); } } return list; }
public void testCreateContextWithPathAndBindings() throws Exception { String oxmString = "org/eclipse/persistence/testing/jaxb/jaxbcontext/eclipselink-oxm.xml"; InputStream oxm = ClassLoader.getSystemClassLoader().getResourceAsStream(oxmString); Map<String, Object> props = new HashMap<String, Object>(); props.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, oxm); // Specify some other, unrelated context path -- we want to ensure that we don't fail // due to lack of ObjectFactory/jaxb.index JAXBContext ctx = JAXBContext.newInstance( "org.eclipse.persistence.testing.oxm.jaxb", ClassLoader.getSystemClassLoader(), props); Employee e = new Employee(); e.id = 6; e.name = "Jeeves Sobs"; e.put("tag", "tag-value"); Document marshalDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Marshaller m = ctx.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(e, marshalDoc); // Make sure OXM was picked up, "tag" property should have been added. Employee e2 = (Employee) ctx.createUnmarshaller().unmarshal(marshalDoc); assertEquals( "OXM file was not processed during context creation.", e.get("tag"), e2.get("tag")); }
/** * Get classes in given package and subpackages, accessible from the context class loader * * @param packageName The base package * @return The classes * @throws ClassNotFoundException * @throws IOException */ protected static List<Class> getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<File>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } List<Class> classList = new ArrayList<Class>(); for (File directory : dirs) { classList.addAll(findClasses(directory, packageName)); } return classList; }
/** * There is a possible case that methods of particular object should be executed with classpath * different from the one implied by the current class' class loader. External system offers * {@link ParametersEnhancer#enhanceLocalProcessing(List)} method for defining that custom * classpath. * * <p>It's also possible that particular implementation of {@link ParametersEnhancer} is compiled * using dependency to classes which are provided by the {@link * ParametersEnhancer#enhanceLocalProcessing(List) expanded classpath}. E.g. a class <code>'A' * </code> might use method of class <code>'B'</code> and 'A' is located at the current * (system/plugin) classpath but <code>'B'</code> is not. We need to reload <code>'A'</code> using * its expanded classpath then, i.e. create new class loaded with that expanded classpath and load * <code>'A'</code> by it. * * <p>This method allows to do that. * * @param clazz custom classpath-aware class which instance should be created (is assumed to have * a no-args constructor) * @param <T> target type * @return newly created instance of the given class loaded by custom classpath-aware loader * @throws IllegalAccessException as defined by reflection processing * @throws InstantiationException as defined by reflection processing * @throws NoSuchMethodException as defined by reflection processing * @throws InvocationTargetException as defined by reflection processing * @throws ClassNotFoundException as defined by reflection processing */ @NotNull public static <T extends ParametersEnhancer> T reloadIfNecessary(@NotNull final Class<T> clazz) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException { T instance = clazz.newInstance(); List<URL> urls = ContainerUtilRt.newArrayList(); instance.enhanceLocalProcessing(urls); if (urls.isEmpty()) { return instance; } final ClassLoader baseLoader = clazz.getClassLoader(); Method method = baseLoader.getClass().getMethod("getUrls"); if (method != null) { //noinspection unchecked urls.addAll((Collection<? extends URL>) method.invoke(baseLoader)); } UrlClassLoader loader = new UrlClassLoader(UrlClassLoader.build().urls(urls).parent(baseLoader.getParent())) { @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.equals(clazz.getName())) { return super.loadClass(name, resolve); } else { try { return baseLoader.loadClass(name); } catch (ClassNotFoundException e) { return super.loadClass(name, resolve); } } } }; //noinspection unchecked return (T) loader.loadClass(clazz.getName()).newInstance(); }
/** Install Add and Remove Buttons into the toolbar */ private void installAddRemovePointButtons() { URL imgURL = ClassLoader.getSystemResource("ch/tbe/pics/plus.gif"); ImageIcon plus = new ImageIcon(imgURL); imgURL = ClassLoader.getSystemResource("ch/tbe/pics/minus.gif"); ImageIcon minus = new ImageIcon(imgURL); add = new JButton(plus); rem = new JButton(minus); add.setToolTipText(workingViewLabels.getString("plus")); rem.setToolTipText(workingViewLabels.getString("minus")); add.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { WorkingView.this.addRemovePoint(true); } }); rem.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { WorkingView.this.addRemovePoint(false); } }); add.setContentAreaFilled(false); add.setBorderPainted(false); rem.setContentAreaFilled(false); rem.setBorderPainted(false); toolbar.add(add); toolbar.add(rem); }
public static Icon getIcon(String iconName) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); URL url = cl.getResource("test/check/icons/" + iconName + ".gif"); if (url != null) return new ImageIcon(url); url = cl.getResource("test/check/icons/" + iconName + ".png"); if (url != null) return new ImageIcon(url); return null; }
@Override public String call(Integer i) throws Exception { ClassLoader ccl = Thread.currentThread().getContextClassLoader(); InputStream in = ccl.getResourceAsStream("test.resource"); byte[] bytes = ByteStreams.toByteArray(in); in.close(); return new String(bytes, 0, bytes.length, "UTF-8"); }
protected File[] getMappingFiles(String matchingsDir, String dir, String exclusionFile) { URL exclusionFileUrl = ClassLoader.getSystemResource(matchingsDir + exclusionFile); File folder = new File(ClassLoader.getSystemResource(matchingsDir + dir).getFile()); if (exclusionFileUrl == null) return folder.listFiles(); File incl = new File(exclusionFileUrl.getFile()); MyFilenameFilter filter = new MyFilenameFilter(incl); return folder.listFiles(filter); }
private String getCsvFilePath() { ClassLoader classLoader = getClass().getClassLoader(); URL csvUrl = classLoader.getResource("category_mapping.csv"); if (csvUrl == null || csvUrl.getFile() == null) { throw new RuntimeException("Bad path to category_mapping.csv"); } return csvUrl.getFile(); }
public ViewportRenderer() { ClassLoader loader = getClass().getClassLoader(); surfaceIcon = new ImageIcon(loader.getResource(IMAGE_BASE + "/vrjuggler-surface-viewport.png")); simIcon = new ImageIcon(loader.getResource(IMAGE_BASE + "/vrjuggler-sim-viewport.png")); scaledSurfaceIcon = new ImageIcon(); scaledSimIcon = new ImageIcon(); }
private static Class<?> loadClass(String className) { try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); return cl.loadClass(className.replace('/', '.')); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }
Class<?> getPluginClass(String packageName, String className) throws NameNotFoundException, ClassNotFoundException { Context pluginContext = this.mAppContext.createPackageContext( packageName, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY); ClassLoader pluginCL = pluginContext.getClassLoader(); return pluginCL.loadClass(className); }
/** * Create MBean for Object. Attempts to create an MBean for the object by searching the package * and class name space. For example an object of the type * * <PRE> * class com.acme.MyClass extends com.acme.util.BaseClass * </PRE> * * Then this method would look for the following classes: * * <UL> * <LI>com.acme.MyClassMBean * <LI>com.acme.jmx.MyClassMBean * <LI>com.acme.util.BaseClassMBean * <LI>com.acme.util.jmx.BaseClassMBean * </UL> * * @param o The object * @return A new instance of an MBean for the object or null. */ public static ModelMBean mbeanFor(Object o) { try { Class oClass = o.getClass(); ClassLoader loader = oClass.getClassLoader(); ModelMBean mbean = null; boolean jmx = false; Class[] interfaces = null; int i = 0; while (mbean == null && oClass != null) { Class focus = interfaces == null ? oClass : interfaces[i]; String pName = focus.getPackage().getName(); String cName = focus.getName().substring(pName.length() + 1); String mName = pName + (jmx ? ".jmx." : ".") + cName + "MBean"; try { Class mClass = loader.loadClass(mName); if (log.isTraceEnabled()) log.trace("mbeanFor " + o + " mClass=" + mClass); mbean = (ModelMBean) mClass.newInstance(); mbean.setManagedResource(o, "objectReference"); if (log.isDebugEnabled()) log.debug("mbeanFor " + o + " is " + mbean); return mbean; } catch (ClassNotFoundException e) { if (e.toString().endsWith("MBean")) { if (log.isTraceEnabled()) log.trace(e.toString()); } else log.warn(LogSupport.EXCEPTION, e); } catch (Error e) { log.warn(LogSupport.EXCEPTION, e); mbean = null; } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); mbean = null; } if (jmx) { if (interfaces != null) { i++; if (i >= interfaces.length) { interfaces = null; oClass = oClass.getSuperclass(); } } else { interfaces = oClass.getInterfaces(); i = 0; if (interfaces == null || interfaces.length == 0) { interfaces = null; oClass = oClass.getSuperclass(); } } } jmx = !jmx; } } catch (Exception e) { LogSupport.ignore(log, e); } return null; }
private void load(File jarFile) { ClassLoader loader; try { loader = URLClassLoader.newInstance( new URL[] {jarFile.toURI().toURL()}, getClass().getClassLoader()); } catch (MalformedURLException e) { Application.LOGGER.error( "Error while loading plugin file - " + jarFile.getAbsolutePath(), e); return; } InputStream stream = loader.getResourceAsStream(MANIFEST_FILE); Properties properties = new Properties(); try { properties.load(stream); } catch (IOException e) { Application.LOGGER.error( "Manifest file - " + MANIFEST_FILE + " not found in the plugin jar - " + jarFile.getAbsolutePath(), e); return; } String pluginClassName = properties.getProperty("plugin.class"); if (!properties.containsKey("plugin.class")) { Application.LOGGER.error( "plugin.class not defined in the manifest file in the plugin jar - " + jarFile.getAbsolutePath()); return; } Class<?> clazz; try { clazz = Class.forName(pluginClassName, true, loader); } catch (ClassNotFoundException e) { Application.LOGGER.error( "Plugin main class - " + pluginClassName + " defined in manifest not found in the plugin jar - " + jarFile.getAbsolutePath(), e); return; } if (!Plugin.class.isAssignableFrom(clazz)) { Application.LOGGER.error( "Plugin class - " + clazz + " is not a Plugin, in the plugin jar - " + jarFile.getAbsolutePath()); } load((Class<? extends Plugin>) clazz, properties); }
@Test public void testLoading() throws Exception { Class<?> type = classLoader.loadClass(Foo.class.getName()); assertThat(type.getClassLoader(), is(classLoader)); assertEquals(classLoader.loadClass(Foo.class.getName()), type); assertNotEquals(Foo.class, type); assertThat(type.getPackage(), notNullValue(Package.class)); assertThat(type.getPackage(), is(Foo.class.getPackage())); }
// {{{ loadFromParent() method private Class loadFromParent(String clazz) throws ClassNotFoundException { Class cls; ClassLoader parentLoader = getClass().getClassLoader(); if (parentLoader != null) cls = parentLoader.loadClass(clazz); else cls = findSystemClass(clazz); return cls; } // }}}
private static InputStream getAsInputStreamFromClassLoader(String filename) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); InputStream is = cl == null ? null : cl.getResourceAsStream(filename); if (is == null) { // check system class loader is = XmlConfigurator.class.getClassLoader().getResourceAsStream(filename); } return is; }
/** * return a checker object which can be used to retrieve the super and interfaces of a class from * its name and classloader, identifying it from the Class instance if it the class is already * loaded otherwise loading the corresponding bytecode and parsing it to obtain the relevant * details. * * @param name the name of the superclass being checked * @param baseLoader the class loader of the subclass's bytecode * @return the requisite checker or null if the class does not need to be checked or cannot be * loaded */ public org.jboss.byteman.agent.check.ClassChecker getClassChecker( String name, ClassLoader baseLoader) { // we would like to just do this // Class superClazz = baseLoader.loadClass(name) // and then access the details using methods of Class // however, this fails because we are in the middle of transforming the subclass and the // classloader // may not have loaded the super. if we force a load now then transforms will not be performed // on // the super class. this may cause us to miss the chance to apply rule injection into the super ClassLoader loader = baseLoader; Class clazz = loadCache.lookupClass(name, loader); if (clazz != null) { return new org.jboss.byteman.agent.check.LoadedClassChecker(clazz); } // ok, instead try loading the bytecode as a resource - user-defined loaders may not support // this but // at least the JVM system and boot loaders should String resourceName = name.replace('.', '/') + ".class"; try { InputStream is; if (baseLoader != null) { is = baseLoader.getResourceAsStream(resourceName); } else { is = ClassLoader.getSystemClassLoader().getResourceAsStream(resourceName); } if (is != null) { int length = is.available(); int count = 0; byte[] bytecode = new byte[length]; while (count < length) { int read = is.read(bytecode, count, length - count); if (read < 0) { throw new IOException("unexpected end of file"); } count += read; } return new org.jboss.byteman.agent.check.BytecodeChecker(bytecode); } else { // throw new IOException("unable to load bytecode for for class " + name); if (isVerbose()) { System.out.println( "Transformer.getClassChecker : unable to load bytecode for for class " + name); } return null; } } catch (IOException e) { // log the exception and return null e.printStackTrace(); return null; } }