List of usage examples for java.lang ClassLoader getSystemClassLoader
@CallerSensitive public static ClassLoader getSystemClassLoader()
From source file:org.apache.cayenne.util.ResourceLocator.java
/** * Returns the ClassLoader associated with this ResourceLocator. *//*from www. j a v a2s.c o m*/ public ClassLoader getClassLoader() { ClassLoader loader = this.classLoader; if (loader == null) { loader = Thread.currentThread().getContextClassLoader(); } if (loader == null) { loader = getClass().getClassLoader(); } if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } return loader; }
From source file:com.all.dht.settings.DhtSettings.java
public static DhtSettings getInstance() throws IOException { if (instance == null) { instance = new DhtSettings(); instance.dhtConfig = new Properties(); instance.dhtConfig// w ww .j a va 2 s.co m .load(ClassLoader.getSystemClassLoader().getResourceAsStream("defaultConfig.properties")); instance.initialize(); } return instance; }
From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java
public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); if (VERBOSE_LOADING) { log.info("Loading Script: " + file.getAbsolutePath()); }/*from w w w . j a v a2s . c o m*/ if (PURGE_ERROR_LOG) { String name = file.getAbsolutePath() + ".error.log"; File errorLog = new File(name); if (errorLog.isFile()) { errorLog.delete(); } } if (engine instanceof Compilable && ATTEMPT_COMPILATION) { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); ScriptContext ctx = engine.getContext(); try { engine.setContext(context); if (USE_COMPILED_CACHE) { CompiledScript cs = _cache.loadCompiledScript(engine, file); cs.eval(context); } else { Compilable eng = (Compilable) engine; CompiledScript cs = eng.compile(reader); cs.eval(context); } } finally { engine.setContext(ctx); setCurrentLoadingScript(null); context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } else { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); try { engine.eval(reader, context); } finally { setCurrentLoadingScript(null); engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } }
From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java
private static void replaceTccl(ClassLoader leakedClassLoader, ClassLoader replacementClassLoader) { for (Thread thread : threads()) { if (thread != null) { ClassLoader cl = thread.getContextClassLoader(); // do identity check to prevent expensive (and potentially dangerous) equals() if (leakedClassLoader == cl) { log.warn("Trying to patch leaked cl [" + leakedClassLoader + "] in thread [" + thread + "]"); ThreadGroup tg = thread.getThreadGroup(); // it's a JVM thread so use the System ClassLoader always boolean debug = log.isDebugEnabled(); if (tg != null && JVM_THREAD_NAMES.contains(tg.getName())) { thread.setContextClassLoader(ClassLoader.getSystemClassLoader()); if (debug) { log.debug("Replaced leaked cl in thread [" + thread + "] with system classloader"); }//w w w .j av a2 s. co m } else { thread.setContextClassLoader(replacementClassLoader); if (debug) { log.debug( "Replaced leaked cl in thread [" + thread + "] with " + replacementClassLoader); } } } } } }
From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java
private void execAppBeforeLoadChecks(final String aAppName, String aAppPath) throws Exception { // parsing app manifest File lManifestFile = new File(aAppPath + "/manifest.json"); if (!lManifestFile.exists() || !lManifestFile.canRead()) { String lMsg = "Unable to load '" + aAppName + "' application. Manifest file no found!"; mLog.error(lMsg);/*from w w w .j a v a 2 s . c o m*/ throw new FileNotFoundException(lMsg); } // 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"); // checking jWebSocket version Manifest.checkJwsVersion(lManifestJSON.getString(Manifest.JWEBSOCKET_VERSION, "1.0.0")); // checking jWebSocket plug-ins dependencies Manifest.checkJwsDependencies( lManifestJSON.getList(Manifest.JWEBSOCKET_PLUGINS_DEPENDENCIES, new ArrayList<String>())); // checking sandbox permissions dependency Manifest.checkPermissions(lManifestJSON.getList(Manifest.PERMISSIONS, new ArrayList()), mSettings.getAppPermissions(aAppName, aAppPath), aAppPath); // validating bootstrap file final File lBootstrap = new File(aAppPath + "/App." + lExt); if (!lBootstrap.exists() || !lBootstrap.canRead()) { String lMsg = "Unable to load '" + aAppName + "' application. Bootstrap file not found!"; mLog.error(lMsg); throw new FileNotFoundException(lMsg); } LocalLoader lClassLoader = new LocalLoader((URLClassLoader) ClassLoader.getSystemClassLoader()); ScriptEngineManager lManager = new ScriptEngineManager(lClassLoader); final ScriptEngine lScriptApp; final BaseScriptApp lApp; 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); } // creating the high level script app instance if ("js".equals(lExt)) { lApp = new JavaScriptApp(this, aAppName, aAppPath, lScriptApp, lClassLoader); } else { String lMsg = "The extension '" + lExt + "' is not currently supported!"; mLog.error(lMsg); throw new Exception(lMsg); } // loading application into security sandbox Tools.doPrivileged(mSettings.getAppPermissions(aAppName, aAppPath), new PrivilegedAction<Object>() { @Override public Object run() { try { // evaluating app content lScriptApp.eval(FileUtils.readFileToString(lBootstrap)); return null; } catch (Exception lEx) { String lAction = (mApps.containsKey(aAppName)) ? "reloaded" : "loaded"; String lMsg = "Script applicaton '" + aAppName + "' not " + lAction + " because it failed the 'before-load' checks: " + lEx.getMessage(); mLog.info(lMsg); throw new RuntimeException(lMsg); } } }); if (mLog.isDebugEnabled()) { mLog.debug(aAppName + "(" + lExt + ") application passed the 'before-load' checks successfully!"); } }
From source file:org.ireland.jnetty.webapp.WebApp.java
/** * add class path of the WebApp to SystemClassLoader(sun.misc.Launcher.AppClassLoader) by reflect NOTICE: only use * for single WebApp mode//from w ww .ja v a 2 s.c o m * * ?webAppClassLoader,,?,?ServletContext(?webAppClassLoader)?, * ?Thread#ContextClassLoader?,,ClassNotFoundException. * * ??,/WEB-INF/classes/WEB-INF/lib/*.jarSystemClassLoader * * @throws Exception * * */ protected ClassLoader addClassPathToSystemClassLoader() throws Exception { URLClassLoader sysClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); // ? Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); // JAVA,?? List<URL> urls = new ArrayList<URL>(); // JarFile: "/WEB-INF/lib" File libPath = new File(getRealPath("/WEB-INF/lib")); if (libPath.isDirectory()) { for (File file : libPath.listFiles()) { if (file.getPath().endsWith(".jar")) { URL url = file.toURI().toURL(); urls.add(url); } } } for (URL jarFile : urls) { // sysClassLoader.classPath(jarFile); method.invoke(sysClassLoader, jarFile); } // ClassPath: "/WEB-INF/classes/" URL classPath = super.getResource("/WEB-INF/classes/"); if (classPath != null) { // sysClassLoader.classPath(classPath); method.invoke(sysClassLoader, classPath); } return sysClassLoader; }
From source file:com.flexoodb.engines.FlexJAXBMappedDBDataEngine.java
private void reviveObject(String parentid, FlexContainer parent, Connection conn, String prefix, boolean revivechildren) throws Exception { Vector v = new Vector(); try {/* ww w. j a va 2s. c o m*/ Class c = parent.getObject().getClass(); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().startsWith("get") && method.getReturnType() != null && !method.getReturnType().getSimpleName().equals("Class")) { Class ret = method.getReturnType(); if (ret.getSimpleName().equals("List")) { Object[] args = null; //List list = (ArrayList) method.invoke(parent.getObject(), args); List list = new Vector<FlexContainer>(); ParameterizedType t = (ParameterizedType) method.getGenericReturnType(); Type type = t.getActualTypeArguments()[0]; String[] s = ("" + type).split(" "); String classname = s[1].substring(s[1].lastIndexOf(".") + 1); String tablename = classname.toLowerCase(); tablename = tablename.endsWith("type") ? tablename.substring(0, tablename.lastIndexOf("type")) : tablename; //FlexElement element = _elements.get(prefix+tablename); FlexElement element = _elements.get(tablename); String idcolumn = element.getAttribute("idcolumn").getValue(); String realtablename = element.getAttribute("realtablename").getValue(); String parentidcolumn = element.getAttribute("parentidcolumn").getValue(); boolean includeidcolumns = element.getAttribute("includeidcolumns").getValue() == null ? false : (element.getAttribute("includeidcolumns").getValue().equalsIgnoreCase("true")); //System.out.println("t:"+tablename+" "+realtablename+" >"+"select * from "+prefix+((realtablename!=null)?realtablename:tablename.toLowerCase())+" where "+parentidcolumn+"=?"+"<"); FlexElement idelement = element.getElementByName(parentidcolumn); PreparedStatement ps = (PreparedStatement) conn.prepareStatement("select * from " + prefix + ((realtablename != null) ? realtablename : tablename.toLowerCase()) + " where " + parentidcolumn + "=?"); //PreparedStatement ps = (PreparedStatement) conn.prepareStatement("select * from "+((realtablename!=null)?realtablename:tablename.toLowerCase())+" where "+parentidcolumn+"=?"); if (idelement.getType().equals("string")) { ps.setString(1, parentid); } else { ps.setInt(1, Integer.parseInt(parentid)); } //System.out.println(">> query:"+ps.toString()); ResultSet rec = ps.executeQuery(); RecordSet res = new RecordSet(rec); // check if a record was found while (res != null && res.next()) { //String id = res.getString("id"); String id = res.getString(idcolumn); //Object o2 = _flexutils.getObject(FlexUtils.getRDBMSRecordAsXML(tablename, res, idcolumn, parentidcolumn,includeidcolumns),Class.forName(s[1])); Object o2 = _flexutils .getObject( FlexUtils.getRDBMSRecordAsXML(tablename, res, idcolumn, parentidcolumn, includeidcolumns), ClassLoader.getSystemClassLoader().loadClass(s[1])); if (id != null && o2 != null) { //instead of adding this in the object's list we add it in the parent flex's //list.add(o2); FlexContainer fo = new FlexContainer(o2); fo.setId(id); fo.setParentId(parentid); list.add(fo); // then we check if this guy has children! enabling this will cause a loop of death //reviveObject(id,o2,conn); } } // finally we add it to the parent flex parent.addChildren(tablename, list); //System.out.println(">>>"+parent.getChildren()); } else if (!ret.getName().startsWith("java") && !ret.getSimpleName().toLowerCase().endsWith("byte[]") && !ret.getSimpleName().toLowerCase().equals("int")) // if complex { String tablename = ret.getSimpleName().toLowerCase(); tablename = tablename.endsWith("type") ? tablename.substring(0, tablename.lastIndexOf("type")) : tablename; FlexElement element = _elements.get(tablename); String idcolumn = element.getAttribute("idcolumn").getValue(); String realtablename = element.getAttribute("realtablename").getValue(); String parentidcolumn = element.getAttribute("parentidcolumn").getValue(); boolean includeidcolumns = element.getAttribute("includeidcolumns").getValue() == null ? false : (element.getAttribute("includeidcolumns").getValue().equalsIgnoreCase("true")); FlexElement idelement = element.getElementByName(parentidcolumn); PreparedStatement ps = (PreparedStatement) conn.prepareStatement("select * from " + prefix + ((realtablename != null) ? realtablename : tablename.toLowerCase()) + " where " + parentidcolumn + "=" + (idelement.getType().equals("string") ? ("'" + parentid + "'") : parentid)); ResultSet rec = ps.executeQuery(); // check if a record was found RecordSet res = new RecordSet(rec); if (res != null && res.size() > 0) { //String id = rec.getString("id"); String id = res.getString(idcolumn); Object o2 = _flexutils.getObject(FlexUtils.getRDBMSRecordAsXML(tablename, res, idcolumn, parentidcolumn, includeidcolumns), ret); if (o2 != null) { String setmethod = "set" + method.getName().substring(3); Object[] args = new Object[1]; args[0] = o2; Class[] cls = new Class[1]; cls[0] = o2.getClass(); Method met = c.getMethod(setmethod, cls); met.invoke(parent.getObject(), args); /*if (revivechildren) { reviveObject(id,o2,conn,prefix,revivechildren); }*/ } if (rec.last()) { break; } } } } } } catch (Exception f) { throw f; } }
From source file:com.xlson.standalonewar.Starter.java
/** * Add url to the system class loader.//from w w w. j av a 2s . com */ public static void appendClasspath(URL url) throws IOException { URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Class sysclass = URLClassLoader.class; try { Method method = sysclass.getDeclaredMethod("addURL", parameters); method.setAccessible(true); method.invoke(sysloader, new Object[] { url }); } catch (Throwable t) { t.printStackTrace(); throw new IOException("Error, could not add URL to system classloader"); } }
From source file:org.opoo.press.impl.SiteImpl.java
private ClassLoader createClassLoader(Config config, Theme theme) { log.debug("Create site ClassLoader."); ClassLoader parent = SiteImpl.class.getClassLoader(); if (parent == null) { parent = ClassLoader.getSystemClassLoader(); }//from w w w. java2 s . co m String sitePluginDir = config.get("plugin_dir"); String themePluginDir = (String) theme.get("plugin_dir"); List<File> classPathEntries = new ArrayList<File>(2); if (StringUtils.isNotBlank(sitePluginDir)) { File sitePlugins = PathUtils.canonical(new File(config.getBasedir(), sitePluginDir)); addClassPathEntries(classPathEntries, sitePlugins); } if (StringUtils.isNotBlank(themePluginDir)) { File themePlugins = PathUtils.canonical(new File(theme.getPath(), themePluginDir)); addClassPathEntries(classPathEntries, themePlugins); } //theme classes File themeClasses = new File(theme.getPath(), "target/classes"); File themeSrc = new File(theme.getPath(), "src"); if (themeSrc.exists() && themeClasses.exists() && themeClasses.isDirectory()) { classPathEntries.add(themeClasses); } //theme target/plugins File themeTargetPlugins = new File(theme.getPath(), "target/plugins"); if (themeTargetPlugins.exists() && themeTargetPlugins.list().length > 0) { addClassPathEntries(classPathEntries, themeTargetPlugins); } if (classPathEntries.isEmpty()) { log.info("No custom classpath entries."); return parent; } URL[] urls = new URL[classPathEntries.size()]; try { for (int i = 0; i < classPathEntries.size(); i++) { urls[i] = classPathEntries.get(i).toURI().toURL(); } } catch (MalformedURLException e) { throw new RuntimeException(e); } return new URLClassLoader(urls, parent); }
From source file:org.psikeds.common.threadlocal.ThreadLocalHelper.java
/** * Get ClassLoader that loaded a given Object. * //www.java2 s .com * @param obj * Object * @return ClassLoader */ private static ClassLoader getClassLoader(final Object obj) { Class<?> clazz = null; ClassLoader cl = null; try { LOGGER.trace("--> getClassLoader(); obj = {}", obj); if (obj != null) { if (obj instanceof Class) { clazz = (Class<?>) obj; } else { clazz = obj.getClass(); } } cl = (clazz == null ? null : clazz.getClassLoader()); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } return cl; } finally { LOGGER.trace("<-- getClassLoader(); clazz = {}; cl = {}", clazz, cl); } }