List of usage examples for java.lang ClassLoader getSystemClassLoader
@CallerSensitive public static ClassLoader getSystemClassLoader()
From source file:com.twosigma.beaker.scala.evaluator.ScalaEvaluator.java
protected ClassLoader newAutoCompleteClassLoader() throws MalformedURLException { logger.debug("creating new autocomplete loader"); acloader_cp = ""; for (int i = 0; i < classPath.size(); i++) { acloader_cp += classPath.get(i); acloader_cp += File.pathSeparatorChar; }// ww w . ja v a 2 s.com acloader_cp += outDir; DynamicClassLoaderSimple cl = new DynamicClassLoaderSimple(ClassLoader.getSystemClassLoader()); cl.addJars(classPath); cl.addDynamicDir(outDir); return cl; }
From source file:jamel.gui.JamelWindow.java
/** * Sets the chart in the specified panel. * @param tabIndex the index of the tab to customize. * @param panelIndex the id of the ChartPanel to customize. * @param chartPanelName the name of the ChartPanel to set. * @throws ClassNotFoundException ...//from w w w .j a va 2 s .com * @throws NoSuchMethodException ... * @throws InvocationTargetException ... * @throws IllegalAccessException ... * @throws InstantiationException ... * @throws SecurityException ... * @throws IllegalArgumentException ... */ public void setChart(int tabIndex, int panelIndex, String chartPanelName) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { final ChartPanel chartPanel = (ChartPanel) Class .forName(chartPanelName, false, ClassLoader.getSystemClassLoader()).getConstructor().newInstance(); ((ChartPanel) ((JPanel) tabbedPane.getComponent(tabIndex)).getComponent(panelIndex)) .setChart(chartPanel.getChart()); }
From source file:edu.stanford.epad.common.plugins.impl.ClassFinderTestUtils.java
public static void dynamicClassLoader() { try {//w ww . jav a2 s .c o m ClassLoader myClassLoader = ClassLoader.getSystemClassLoader(); // Step 2: Define a class to be loaded. String classNameToBeLoaded = "edu.stanford.epad.plugins.first.FirstHandler"; // Step 3: Load the class Class<?> myClass = myClassLoader.loadClass(classNameToBeLoaded); if (myClass != null) { logger.info("dynamicClassLoader found FirstHandler."); // Step 4: create a new instance of that class @SuppressWarnings("unused") Object whatInstance = myClass.newInstance(); } else { logger.info("FirstHandler was not found"); } } catch (Exception e) { logger.warning(e.getMessage(), e); } catch (IncompatibleClassChangeError err) { logger.warning(err.getMessage(), err); } }
From source file:com.springframework.beans.BeanUtils.java
/** * Find a JavaBeans PropertyEditor following the 'Editor' suffix convention * (e.g. "mypackage.MyDomainClass" -> "mypackage.MyDomainClassEditor"). * <p>Compatible to the standard JavaBeans convention as implemented by * {@link java.beans.PropertyEditorManager} but isolated from the latter's * registered default editors for primitive types. * @param targetType the type to find an editor for * @return the corresponding editor, or {@code null} if none found *//*w w w . ja va 2 s. co m*/ public static PropertyEditor findEditorByConvention(Class<?> targetType) { if (targetType == null || targetType.isArray() || unknownEditorTypes.contains(targetType)) { return null; } ClassLoader cl = targetType.getClassLoader(); if (cl == null) { try { cl = ClassLoader.getSystemClassLoader(); if (cl == null) { return null; } } catch (Throwable ex) { // e.g. AccessControlException on Google App Engine if (logger.isDebugEnabled()) { logger.debug("Could not access system ClassLoader: " + ex); } return null; } } String editorName = targetType.getName() + "Editor"; try { Class<?> editorClass = cl.loadClass(editorName); if (!PropertyEditor.class.isAssignableFrom(editorClass)) { if (logger.isWarnEnabled()) { logger.warn("Editor class [" + editorName + "] does not implement [java.beans.PropertyEditor] interface"); } unknownEditorTypes.add(targetType); return null; } return (PropertyEditor) instantiateClass(editorClass); } catch (ClassNotFoundException ex) { if (logger.isDebugEnabled()) { logger.debug("No property editor [" + editorName + "] found for type " + targetType.getName() + " according to 'Editor' suffix convention"); } unknownEditorTypes.add(targetType); return null; } }
From source file:org.apache.hadoop.hbase.TestClassFinder.java
/** * Makes a jar out of some class files. Unfortunately it's very tedious. * @param filesInJar Files created via compileTestClass. * @return path to the resulting jar file. *///ww w . j av a2s . c om private static String packageAndLoadJar(FileAndPath... filesInJar) throws Exception { // First, write the bogus jar file. String path = basePath + "jar" + jarCounter.incrementAndGet() + ".jar"; Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); FileOutputStream fos = new FileOutputStream(path); JarOutputStream jarOutputStream = new JarOutputStream(fos, manifest); // Directory entries for all packages have to be added explicitly for // resources to be findable via ClassLoader. Directory entries must end // with "/"; the initial one is expected to, also. Set<String> pathsInJar = new HashSet<String>(); for (FileAndPath fileAndPath : filesInJar) { String pathToAdd = fileAndPath.path; while (pathsInJar.add(pathToAdd)) { int ix = pathToAdd.lastIndexOf('/', pathToAdd.length() - 2); if (ix < 0) { break; } pathToAdd = pathToAdd.substring(0, ix); } } for (String pathInJar : pathsInJar) { jarOutputStream.putNextEntry(new JarEntry(pathInJar)); jarOutputStream.closeEntry(); } for (FileAndPath fileAndPath : filesInJar) { File file = fileAndPath.file; jarOutputStream.putNextEntry(new JarEntry(fileAndPath.path + file.getName())); byte[] allBytes = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(allBytes); fis.close(); jarOutputStream.write(allBytes); jarOutputStream.closeEntry(); } jarOutputStream.close(); fos.close(); // Add the file to classpath. File jarFile = new File(path); assertTrue(jarFile.exists()); URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class }); method.setAccessible(true); method.invoke(urlClassLoader, new Object[] { jarFile.toURI().toURL() }); return jarFile.getAbsolutePath(); }
From source file:com.app.server.SARDeployer.java
/** * This method extracts the SAR archive and configures for the SAR and starts the services * @param file//from ww w . j a v a2 s . c om * @param warDirectoryPath * @throws IOException */ public void extractSarDeploy(ClassLoader cL, Object... args) throws IOException { CopyOnWriteArrayList classPath = null; File file = null; String fileName = ""; String fileWithPath = ""; if (args[0] instanceof File) { classPath = new CopyOnWriteArrayList(); file = (File) args[0]; fileWithPath = file.getAbsolutePath(); ZipFile zip = new ZipFile(file); ZipEntry ze = null; fileName = file.getName(); fileName = fileName.substring(0, fileName.indexOf('.')); fileName += "sar"; String fileDirectory; Enumeration<? extends ZipEntry> entries = zip.entries(); int numBytes; while (entries.hasMoreElements()) { ze = entries.nextElement(); // //log.info("Unzipping " + ze.getName()); String filePath = serverConfig.getDeploydirectory() + "/" + fileName + "/" + ze.getName(); if (!ze.isDirectory()) { fileDirectory = filePath.substring(0, filePath.lastIndexOf('/')); } else { fileDirectory = filePath; } // //log.info(fileDirectory); createDirectory(fileDirectory); if (!ze.isDirectory()) { FileOutputStream fout = new FileOutputStream(filePath); byte[] inputbyt = new byte[8192]; InputStream istream = zip.getInputStream(ze); while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) { fout.write(inputbyt, 0, numBytes); } fout.close(); istream.close(); if (ze.getName().endsWith(".jar")) { classPath.add(filePath); } } } zip.close(); } else if (args[0] instanceof FileObject) { FileObject fileObj = (FileObject) args[0]; fileName = fileObj.getName().getBaseName(); try { fileWithPath = fileObj.getURL().toURI().toString(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } fileName = fileName.substring(0, fileName.indexOf('.')); fileName += "sar"; classPath = unpack(fileObj, new File(serverConfig.getDeploydirectory() + "/" + fileName + "/"), (StandardFileSystemManager) args[1]); } URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = loader.getURLs(); WebClassLoader sarClassLoader; if (cL != null) { sarClassLoader = new WebClassLoader(urls, cL); } else { sarClassLoader = new WebClassLoader(urls); } for (int index = 0; index < classPath.size(); index++) { // log.info("file:"+classPath.get(index)); sarClassLoader.addURL(new URL("file:" + classPath.get(index))); } sarClassLoader.addURL(new URL("file:" + serverConfig.getDeploydirectory() + "/" + fileName + "/")); //log.info(sarClassLoader.geturlS()); sarsMap.put(fileWithPath, sarClassLoader); try { Sar sar = (Sar) sardigester.parse(new InputSource(new FileInputStream( serverConfig.getDeploydirectory() + "/" + fileName + "/META-INF/" + "mbean-service.xml"))); CopyOnWriteArrayList mbeans = sar.getMbean(); //log.info(mbeanServer); ObjectName objName, classLoaderObjectName = new ObjectName("com.app.server:classLoader=" + fileName); if (!mbeanServer.isRegistered(classLoaderObjectName)) { mbeanServer.registerMBean(sarClassLoader, classLoaderObjectName); } else { mbeanServer.unregisterMBean(classLoaderObjectName); mbeanServer.registerMBean(sarClassLoader, classLoaderObjectName); ; } for (int index = 0; index < mbeans.size(); index++) { Mbean mbean = (Mbean) mbeans.get(index); //log.info(mbean.getObjectname()); //log.info(mbean.getCls()); objName = new ObjectName(mbean.getObjectname()); Class service = sarClassLoader.loadClass(mbean.getCls()); if (mbeanServer.isRegistered(objName)) { //mbs.invoke(objName, "stopService", null, null); //mbs.invoke(objName, "destroy", null, null); mbeanServer.unregisterMBean(objName); } mbeanServer.createMBean(service.getName(), objName, classLoaderObjectName); //mbs.registerMBean(obj, objName); CopyOnWriteArrayList attrlist = mbean.getMbeanAttribute(); if (attrlist != null) { for (int count = 0; count < attrlist.size(); count++) { MBeanAttribute attr = (MBeanAttribute) attrlist.get(count); Attribute mbeanattribute = new Attribute(attr.getName(), attr.getValue()); mbeanServer.setAttribute(objName, mbeanattribute); } } Attribute mbeanattribute = new Attribute("ObjectName", objName); mbeanServer.setAttribute(objName, mbeanattribute); if (((String) mbeanServer.getAttribute(objName, "Deployer")).equals("true")) { mbeanServer.invoke(objName, "init", new Object[] { deployerList }, new String[] { Vector.class.getName() }); } mbeanServer.invoke(objName, "init", new Object[] { serviceList, serverConfig, mbeanServer }, new String[] { Vector.class.getName(), ServerConfig.class.getName(), MBeanServer.class.getName() }); mbeanServer.invoke(objName, "start", null, null); serviceListObjName.put(fileWithPath, objName); } } catch (Exception e) { log.error("Could not able to deploy sar archive " + fileWithPath, e); // TODO Auto-generated catch block //e.printStackTrace(); } }
From source file:me.piebridge.prevent.ui.UserGuideActivity.java
private static Integer getXposedVersion() { try {//from w w w .j a v a 2s . com return (Integer) Class .forName("de.robv.android.xposed.XposedBridge", false, ClassLoader.getSystemClassLoader()) .getField("XPOSED_BRIDGE_VERSION").get(null); } catch (Throwable t) { // NOSONAR return 0; } }
From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java
/** * Loads an script application.//from www .j a v a 2 s .c o m * * @param aAppName The application name * @param aAppPath The application home path * @param aHotLoad * @return * @throws Exception */ private void loadApp(final String aAppName, String aAppPath, boolean aHotLoad) throws Exception { // notifying before app reload event here BaseScriptApp lScript = mApps.get(aAppName); if (null != lScript) { lScript.notifyEvent(BaseScriptApp.EVENT_BEFORE_APP_RELOAD, new Object[] { aHotLoad }); if (!aHotLoad) { destroyAppBeans(lScript); } } // parsing app manifest File lManifestFile = new File(aAppPath + "/manifest.json"); // parsing app manifest file ObjectMapper lMapper = new ObjectMapper(); Map<String, Object> lTree = lMapper.readValue(lManifestFile, Map.class); Token lManifestJSON = TokenFactory.createToken(); lManifestJSON.setMap(lTree); // getting script language extension String lExt = lManifestJSON.getString(Manifest.LANGUAGE_EXT, "js"); // validating bootstrap file final File lBootstrap = new File(aAppPath + "/App." + lExt); // support hot app load if (aHotLoad && mApps.containsKey(aAppName)) { try { // loading app mApps.get(aAppName).eval(lBootstrap.getPath()); } catch (ScriptException lEx) { mLog.error("Script applicaton '" + aAppName + "' failed to start: " + lEx.getMessage()); mApps.remove(aAppName); throw new ScriptException(lEx.getMessage()); } } else { LocalLoader lClassLoader = new LocalLoader((URLClassLoader) ClassLoader.getSystemClassLoader()); ScriptEngineManager lManager = new ScriptEngineManager(lClassLoader); final ScriptEngine lScriptApp; if ("js".equals(lExt)) { // making "nashorn" the default engine for JavaScript if (null != lManager.getEngineByName("nashorn")) { lScriptApp = lManager.getEngineByName("nashorn"); } else { lScriptApp = lManager.getEngineByExtension(lExt); } } else { lScriptApp = lManager.getEngineByExtension(lExt); } // crating the high level script app instance if ("js".equals(lExt)) { mApps.put(aAppName, new JavaScriptApp(this, aAppName, aAppPath, lScriptApp, lClassLoader)); } else { String lMsg = "The extension '" + lExt + "' is not currently supported!"; mLog.error(lMsg); throw new Exception(lMsg); } final BaseScriptApp lApp = mApps.get(aAppName); // loading application into security sandbox Tools.doPrivileged(mSettings.getAppPermissions(aAppName, aAppPath), new PrivilegedAction<Object>() { @Override public Object run() { try { // loading app lApp.eval(lBootstrap.getPath()); return null; } catch (Exception lEx) { mLog.error("Script applicaton '" + aAppName + "' failed to start: " + lEx.getMessage()); mApps.remove(aAppName); throw new RuntimeException(lEx); } } }); } // notifying app loaded event mApps.get(aAppName).notifyEvent(BaseScriptApp.EVENT_APP_LOADED, new Object[] { aHotLoad }); if (mLog.isDebugEnabled()) { mLog.debug(aAppName + "(" + lExt + ") application loaded successfully!"); } }
From source file:org.objectstyle.cayenne.util.ResourceLocator.java
/** * Sets ClassLoader used to locate resources. If <code>null</code> is * passed, the ClassLoader of the ResourceLocator class will be used. *//*from ww w . j a va2s. com*/ public void setClassLoader(ClassLoader classLoader) { if (classLoader == null) { classLoader = this.getClass().getClassLoader(); if (classLoader == null) { classLoader = ClassLoader.getSystemClassLoader(); } } this.classLoader = classLoader; }
From source file:org.columba.core.main.Bootstrap.java
/** * This hacks the classloader to adjust the classpath for convenient native * support./*from w w w.ja v a2 s . c om*/ * <p> * I've cleaned this up using our new global class loader. This way we only * add a few new <code>URLs</code> to our class loader instead of * modifying the system class loader using reflection. * * @author tstich,fdietz * * @throws Exception */ private void addNativeJarsToClasspath() throws Exception { File nativeDir; String libDir; if (OSInfo.isAMD64Bit()) libDir = "amd64"; else libDir = "lib"; // Setup the path // Platform maintainers: add your platform here // see also initPlatformServices() method if (OSInfo.isLinux()) nativeDir = new File("native/linux/" + libDir); else if (OSInfo.isMac()) nativeDir = new File("native/mac/" + libDir); else if (OSInfo.isWin32Platform()) nativeDir = new File("native/win32/" + libDir); else { LOG.info("Native support for Platform not available."); return; } // Find all native jars File[] nativeJars = nativeDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith("jar") || name.endsWith("jnilib"); } }); if (nativeJars == null) return; // @author: fdietz // // The following line is not working - just don't know why // Main.mainClassLoader.addURLs((URL[]) urlList.toArray(new URL[0])); // // WORKAROUND: // // Modify the system class loader instead - horrible! But it works! // Get the current classpath from the sysloader // through reflection URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Field ucp = URLClassLoader.class.getDeclaredField("ucp"); ucp.setAccessible(true); URLClassPath currentCP = (URLClassPath) ucp.get(sysloader); URL[] currentURLs = currentCP.getURLs(); // add all native jars List<URL> urlList = new ArrayList<URL>(); for (int i = 0; i < nativeJars.length; i++) { urlList.add(nativeJars[i].toURL()); } // add the old classpath for (int i = 0; i < currentURLs.length; i++) { urlList.add(currentURLs[i]); } // replace with the modified classpath ucp.set(sysloader, new URLClassPath((URL[]) urlList.toArray(new URL[0]))); }