void enableLionFS() { try { String version = System.getProperty("os.version"); String[] tokens = version.split("\\."); int major = Integer.parseInt(tokens[0]), minor = 0; if (tokens.length > 1) minor = Integer.parseInt(tokens[1]); if (major < 10 || (major == 10 && minor < 7)) throw new Exception("Operating system version is " + version); Class fsuClass = Class.forName("com.apple.eawt.FullScreenUtilities"); Class argClasses[] = new Class[] {Window.class, Boolean.TYPE}; Method setWindowCanFullScreen = fsuClass.getMethod("setWindowCanFullScreen", argClasses); setWindowCanFullScreen.invoke(fsuClass, this, true); Class fsListenerClass = Class.forName("com.apple.eawt.FullScreenListener"); InvocationHandler fsHandler = new MyInvocationHandler(cc); Object proxy = Proxy.newProxyInstance( fsListenerClass.getClassLoader(), new Class[] {fsListenerClass}, fsHandler); argClasses = new Class[] {Window.class, fsListenerClass}; Method addFullScreenListenerTo = fsuClass.getMethod("addFullScreenListenerTo", argClasses); addFullScreenListenerTo.invoke(fsuClass, this, proxy); canDoLionFS = true; } catch (Exception e) { vlog.debug("Could not enable OS X 10.7+ full-screen mode:"); vlog.debug(" " + e.toString()); } }
/** * Construct a client-side proxy object that implements the named protocol, talking to a server at * the named address. * * @param <T> */ @Override @SuppressWarnings("unchecked") public <T> ProtocolProxy<T> getProxy( Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout, RetryPolicy connectionRetryPolicy) throws IOException { if (connectionRetryPolicy != null) { throw new UnsupportedOperationException( "Not supported: connectionRetryPolicy=" + connectionRetryPolicy); } T proxy = (T) Proxy.newProxyInstance( protocol.getClassLoader(), new Class[] {protocol}, new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout)); return new ProtocolProxy<T>(protocol, proxy, true); }
/** * Force initialization of the static members. As of Java 5, referencing a class doesn't force it * to initialize. Since this class requires that the classes be initialized to declare their * comparators, we force that initialization to happen. * * @param cls the class to initialize */ private static void forceInit(Class<?> cls) { try { Class.forName(cls.getName(), true, cls.getClassLoader()); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Can't initialize class " + cls, e); } }
/** * Creates a new proxy with the specified URL. The returned object is a proxy with the interface * specified by api. * * <pre> * String url = "http://localhost:8080/ejb/hello"); * HelloHome hello = (HelloHome) factory.create(HelloHome.class, url); * </pre> * * @param api the interface the proxy class needs to implement * @param url the URL where the client object is located. * @return a proxy to the object with the specified interface. */ public Object create(Class api, String urlName, ClassLoader loader) throws MalformedURLException { URL url = new URL(urlName); HessianProxy handler = new HessianProxy(this, url); return Proxy.newProxyInstance( api.getClassLoader(), new Class[] {api, HessianRemoteObject.class}, handler); }
public static Resource myres(Class<?> c) { ClassLoader cl = c.getClassLoader(); if (cl instanceof Resource.ResClassLoader) { return (((Resource.ResClassLoader) cl).getres()); } else { return (null); } }
/** * Indicates if a class is recompilable. Recompilable means, that the classloader will try to * locate a groovy source file for this class and then compile it again, adding the resulting * class as entry to the cache. Giving null as class is like a recompilation, so the method should * always return true here. Only classes that are implementing GroovyObject are compilable and * only if the timestamp in the class is lower than Long.MAX_VALUE. * * <p>NOTE: First the parent loaders will be asked and only if they don't return a class the * recompilation will happen. Recompilation also only happen if the source file is newer. * * @param cls the class to be tested. If null the method should return true * @return true if the class should be compiled again * @see #isSourceNewer(URL, Class) */ protected boolean isRecompilable(Class cls) { if (cls == null) return true; if (cls.getClassLoader() == this) return false; if (recompile == null && !config.getRecompileGroovySource()) return false; if (recompile != null && !recompile) return false; if (!GroovyObject.class.isAssignableFrom(cls)) return false; long timestamp = getTimeStamp(cls); if (timestamp == Long.MAX_VALUE) return false; return true; }
public static void main(String[] args) throws Exception { Class thisClass = MethodResultTest.class; Class exoticClass = Exotic.class; String exoticClassName = Exotic.class.getName(); ClassLoader testClassLoader = thisClass.getClassLoader(); if (!(testClassLoader instanceof URLClassLoader)) { System.out.println("TEST INVALID: Not loaded by a " + "URLClassLoader: " + testClassLoader); System.exit(1); } URLClassLoader tcl = (URLClassLoader) testClassLoader; URL[] urls = tcl.getURLs(); ClassLoader shadowLoader = new ShadowLoader( urls, testClassLoader, new String[] { exoticClassName, ExoticMBeanInfo.class.getName(), ExoticException.class.getName() }); Class cl = shadowLoader.loadClass(exoticClassName); if (cl == exoticClass) { System.out.println( "TEST INVALID: Shadow class loader loaded " + "same class as test class loader"); System.exit(1); } Thread.currentThread().setContextClassLoader(shadowLoader); ObjectName on = new ObjectName("a:b=c"); MBeanServer mbs = MBeanServerFactory.newMBeanServer(); mbs.createMBean(Thing.class.getName(), on); final String[] protos = {"rmi", "iiop", "jmxmp"}; boolean ok = true; for (int i = 0; i < protos.length; i++) { try { ok &= test(protos[i], mbs, on); System.out.println(); } catch (Exception e) { System.out.println("TEST FAILED WITH EXCEPTION:"); e.printStackTrace(System.out); ok = false; } } if (ok) System.out.println("Test passed"); else { System.out.println("TEST FAILED"); System.exit(1); } }
public static File getResourceAsFile(String name, Class<?> thisClass) { ClassLoader classLoader = thisClass.getClassLoader(); try { //noinspection ConstantConditions // String path = classLoader.getResource("").getPath(); // ///C:/Users/tenti/Desktop/Projects/gate-basic/target/test-classes/ return new File(classLoader.getResource(name).getFile()); } catch (NullPointerException e) { try { // return new // File(Thread.currentThread().getContextClassLoader().getResource(name).getFile()); // ClassLoader classLoader = Config.class.getClassLoader(); // URL resource = classLoader.getResource(name); // String path = Paths.get(resource.toURI()).toAbsolutePath().toString(); File file = null; URL url = null; if (classLoader != null) { url = classLoader.getResource(name); } if (url == null) { url = ClassLoader.getSystemResource(name); } if (url != null) { try { file = new File(url.toURI()); } catch (URISyntaxException e5) { file = new File(url.getPath()); } } if (file == null) { file = getResourceAsFileFromBuildFolder(name); } // return new File(path); return file; } catch (NullPointerException | IOException e2) { logger.error(e2.getMessage(), e2); return new File(""); } } }
/** 获取类的class文件位置的URL。这个方法是本类最基础的方法,供其它方法调用。 */ public URL getClassLocationURL(final Class cls) { if (cls == null) { throw new IllegalArgumentException("class that input is null"); } URL result = null; final String clsAsResource = cls.getName().replace('.', '/').concat(".class"); final ProtectionDomain pd = cls.getProtectionDomain(); if (pd != null) { final CodeSource cs = pd.getCodeSource(); if (cs != null) { result = cs.getLocation(); } if (result != null) { if ("file".equals(result.getProtocol())) { try { if (result.toExternalForm().endsWith(".jar") || result.toExternalForm().endsWith(".zip")) { result = new URL( "jar:".concat(result.toExternalForm()).concat("!/").concat(clsAsResource)); } else if (new File(result.getFile()).isDirectory()) { result = new URL(result, clsAsResource); } } catch (MalformedURLException ignore) { } } } } if (result == null) { final ClassLoader clsLoader = cls.getClassLoader(); result = clsLoader != null ? clsLoader.getResource(clsAsResource) : ClassLoader.getSystemResource(clsAsResource); } return result; }
/** * Construct a client-side proxy that implements the named protocol, talking to a server at the * named address. * * @param protocol protocol * @param clientVersion client's version * @param addr server address * @param ticket security ticket * @param conf configuration * @param factory socket factory * @param rpcTimeout max time for each rpc; 0 means no timeout * @return the proxy * @throws IOException if any error occurs */ @SuppressWarnings("unchecked") public static <T extends VersionedProtocol> ProtocolProxy<T> getProtocolProxy( Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout) throws IOException { T proxy = (T) Proxy.newProxyInstance( protocol.getClassLoader(), new Class[] {protocol}, new Invoker(addr, ticket, conf, factory, rpcTimeout, protocol)); String protocolName = protocol.getName(); try { ProtocolSignature serverInfo = proxy.getProtocolSignature( protocolName, clientVersion, ProtocolSignature.getFingerprint(protocol.getMethods())); return new ProtocolProxy<T>(protocol, proxy, serverInfo.getMethods()); } catch (RemoteException re) { IOException ioe = re.unwrapRemoteException(IOException.class); if (ioe.getMessage() .startsWith(IOException.class.getName() + ": " + NoSuchMethodException.class.getName())) { // Method getProtocolSignature not supported long serverVersion = proxy.getProtocolVersion(protocol.getName(), clientVersion); if (serverVersion == clientVersion) { return new ProtocolProxy<T>(protocol, proxy, null); } throw new VersionMismatch(protocolName, clientVersion, serverVersion, proxy); } throw re; } }
public static String getClassResource(Class<?> klass) { return klass .getClassLoader() .getResource(klass.getName().replace('.', '/') + ".class") .toString(); }
static void initializePlugins(@Nullable StartupProgress progress) { configureExtensions(); final IdeaPluginDescriptorImpl[] pluginDescriptors = loadDescriptors(progress); final Class callerClass = ReflectionUtil.findCallerClass(1); assert callerClass != null; final ClassLoader parentLoader = callerClass.getClassLoader(); final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>(); final HashMap<String, String> disabledPluginNames = new HashMap<String, String>(); for (IdeaPluginDescriptorImpl descriptor : pluginDescriptors) { if (descriptor.getPluginId().getIdString().equals(CORE_PLUGIN_ID)) { final List<String> modules = descriptor.getModules(); if (modules != null) { ourAvailableModules.addAll(modules); } } if (!shouldSkipPlugin(descriptor, pluginDescriptors)) { result.add(descriptor); } else { descriptor.setEnabled(false); disabledPluginNames.put(descriptor.getPluginId().getIdString(), descriptor.getName()); initClassLoader(parentLoader, descriptor); } } prepareLoadingPluginsErrorMessage(filterBadPlugins(result, disabledPluginNames)); final Map<PluginId, IdeaPluginDescriptorImpl> idToDescriptorMap = new HashMap<PluginId, IdeaPluginDescriptorImpl>(); for (final IdeaPluginDescriptorImpl descriptor : result) { idToDescriptorMap.put(descriptor.getPluginId(), descriptor); } final IdeaPluginDescriptor corePluginDescriptor = idToDescriptorMap.get(PluginId.getId(CORE_PLUGIN_ID)); assert corePluginDescriptor != null : CORE_PLUGIN_ID + " not found; platform prefix is " + System.getProperty(PlatformUtilsCore.PLATFORM_PREFIX_KEY); for (IdeaPluginDescriptorImpl descriptor : result) { if (descriptor != corePluginDescriptor) { descriptor.insertDependency(corePluginDescriptor); } } mergeOptionalConfigs(idToDescriptorMap); // sort descriptors according to plugin dependencies Collections.sort(result, getPluginDescriptorComparator(idToDescriptorMap)); for (int i = 0; i < result.size(); i++) { ourId2Index.put(result.get(i).getPluginId(), i); } int i = 0; for (final IdeaPluginDescriptorImpl pluginDescriptor : result) { if (pluginDescriptor.getPluginId().getIdString().equals(CORE_PLUGIN_ID) || pluginDescriptor.isUseCoreClassLoader()) { pluginDescriptor.setLoader(parentLoader, true); } else { final List<File> classPath = pluginDescriptor.getClassPath(); final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds(); final ClassLoader[] parentLoaders = getParentLoaders(idToDescriptorMap, dependentPluginIds); final ClassLoader pluginClassLoader = createPluginClassLoader( classPath.toArray(new File[classPath.size()]), parentLoaders.length > 0 ? parentLoaders : new ClassLoader[] {parentLoader}, pluginDescriptor); pluginDescriptor.setLoader(pluginClassLoader, true); } pluginDescriptor.registerExtensions(); if (progress != null) { progress.showProgress( "", PLUGINS_PROGRESS_MAX_VALUE + (i++ / (float) result.size()) * 0.35f); } } ourPlugins = pluginDescriptors; }
public void testToClass() throws Exception { ClassPool cp = ClassPool.getDefault(); CtClass cc = cp.makeClass("test2.ToClassTest"); Class c = cc.toClass(); assertEquals(getClass().getClassLoader(), c.getClassLoader()); }
/** {@inheritDoc} */ @Override public ClassLoader classLoader() { return p2pCls.getClassLoader(); }
/** * Loads a resource relative to a specific class into a byte array. * * @param c Class (resource must come from same classloader) * @param sName Name of resource (relative path to class) * @return Byte array containing file in memory * @throws IOException If it doesn't exist or there is any other error loading */ public static byte[] loadResource(Class c, String sName) throws IOException { return loadResource( c.getClassLoader(), "/" + c.getName().replace('.', '/').replaceFirst("/[^/]*$", "") + "/" + sName); }