List of usage examples for java.lang Class getClassLoader
@CallerSensitive
@ForceInline
public ClassLoader getClassLoader()
From source file:Main.java
/** * Load a given resources. <p/> This method will try to load the resources * using the following methods (in order): * <ul>// www.ja va 2s . c o m * <li>From Thread.currentThread().getContextClassLoader() * <li>From ClassLoaderUtil.class.getClassLoader() * <li>callingClass.getClassLoader() * </ul> * * @param resourceName The name of the resource to load * @param callingClass The Class object of the calling object */ public static List<URL> getResources(String resourceName, Class callingClass) { List<URL> ret = new ArrayList<URL>(); Enumeration<URL> urls = new Enumeration<URL>() { public boolean hasMoreElements() { return false; } public URL nextElement() { return null; } }; try { urls = Thread.currentThread().getContextClassLoader().getResources(resourceName); } catch (IOException e) { //ignore } if (!urls.hasMoreElements() && resourceName.startsWith("/")) { //certain classloaders need it without the leading / try { urls = Thread.currentThread().getContextClassLoader().getResources(resourceName.substring(1)); } catch (IOException e) { // ignore } } ClassLoader cluClassloader = Main.class.getClassLoader(); if (cluClassloader == null) { cluClassloader = ClassLoader.getSystemClassLoader(); } if (!urls.hasMoreElements()) { try { urls = cluClassloader.getResources(resourceName); } catch (IOException e) { // ignore } } if (!urls.hasMoreElements() && resourceName.startsWith("/")) { //certain classloaders need it without the leading / try { urls = cluClassloader.getResources(resourceName.substring(1)); } catch (IOException e) { // ignore } } if (!urls.hasMoreElements()) { ClassLoader cl = callingClass.getClassLoader(); if (cl != null) { try { urls = cl.getResources(resourceName); } catch (IOException e) { // ignore } } } if (!urls.hasMoreElements()) { URL url = callingClass.getResource(resourceName); if (url != null) { ret.add(url); } } while (urls.hasMoreElements()) { ret.add(urls.nextElement()); } if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) { return getResources('/' + resourceName, callingClass); } return ret; }
From source file:dpfmanager.shell.modules.report.core.ReportGenerator.java
/** * Copies the HTML folder to the reports folder. * * @param name the name/* ww w. j a v a 2 s . c o m*/ */ private void copyHtmlFolder(String name) { // Get the target folder File nameFile = new File(name); String absolutePath = nameFile.getAbsolutePath(); String targetPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator)); File target = new File(targetPath + File.separator + "html"); if (!target.exists()) { target.mkdirs(); } // Copy the html folder to target String pathStr = "./src/main/resources/html"; Path path = Paths.get(pathStr); if (Files.exists(path)) { // Look in current dir File folder = new File(pathStr); if (folder.exists() && folder.isDirectory()) { try { copyDirectory(folder, target); } catch (IOException e) { e.printStackTrace(); } } } else { // Look in JAR CodeSource src = ReportGenerator.class.getProtectionDomain().getCodeSource(); if (src != null) { String jarFolder; try { Class cls = ReportGenerator.class; ClassLoader cLoader = cls.getClassLoader(); List<String> arrayFiles = new ArrayList<>(); List<File> arrayFolders = new ArrayList<>(); //files in js folder arrayFiles.add("html/js/bootstrap.min.js"); arrayFiles.add("html/js/jquery-1.9.1.min.js"); arrayFiles.add("html/js/jquery.flot.pie.min.js"); arrayFiles.add("html/js/jquery.flot.min.js"); //files in img folder arrayFiles.add("html/img/noise.jpg"); arrayFiles.add("html/img/logo.png"); arrayFiles.add("html/img/logo - copia.png"); arrayFiles.add("html/img/check_radio_sheet.png"); //files in fonts folder arrayFiles.add("html/fonts/fontawesome-webfont.woff2"); arrayFiles.add("html/fonts/fontawesome-webfont.woff"); arrayFiles.add("html/fonts/fontawesome-webfont.ttf"); arrayFiles.add("html/fonts/fontawesome-webfont.svg"); arrayFiles.add("html/fonts/fontawesome-webfont.eot"); arrayFiles.add("html/fonts/fontello.woff2"); arrayFiles.add("html/fonts/fontello.woff"); arrayFiles.add("html/fonts/fontello.ttf"); arrayFiles.add("html/fonts/fontello.svg"); arrayFiles.add("html/fonts/fontello.eot"); arrayFiles.add("html/fonts/FontAwesome.otf"); arrayFiles.add("html/fonts/Roboto-Bold.ttf"); //files in css folder arrayFiles.add("html/css/font-awesome.css"); arrayFiles.add("html/css/default.css"); arrayFiles.add("html/css/bootstrap.css"); arrayFiles.add("html/css/fontello.css"); arrayFolders.add(new File(targetPath + File.separator + "html/js/")); arrayFolders.add(new File(targetPath + File.separator + "html/img/")); arrayFolders.add(new File(targetPath + File.separator + "html/fonts/")); arrayFolders.add(new File(targetPath + File.separator + "html/css/")); //if originals folders not exists for (File item : arrayFolders) { if (!item.exists()) { item.mkdirs(); } } //copy files for (String filePath : arrayFiles) { InputStream in = cLoader.getResourceAsStream(filePath); int readBytes; byte[] buffer = new byte[4096]; jarFolder = targetPath + File.separator; File prova = new File(jarFolder + filePath); if (!prova.exists()) { prova.createNewFile(); } OutputStream resStreamOut = new FileOutputStream(prova, false); while ((readBytes = in.read(buffer)) > 0) { resStreamOut.write(buffer, 0, readBytes); } } } catch (IOException e) { context.send(BasicConfig.MODULE_MESSAGE, new ExceptionMessage("IOException", e)); } } } }
From source file:org.apache.hadoop.hbase.ipc.ProtobufRpcEngine.java
@Override public VersionedProtocol getProxy(Class<? extends VersionedProtocol> protocol, long clientVersion, InetSocketAddress addr, User ticket, Configuration conf, SocketFactory factory, int rpcTimeout) throws IOException { final Invoker invoker = new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout); return (VersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol }, invoker);//from www. java 2 s. com }
From source file:com.google.gdt.eclipse.designer.util.GwtInvocationEvaluatorInterceptor.java
/** * Tweaks arguments to fix know problem cases. *//*from w w w .ja v a 2s . co m*/ private void fixArguments(Class<?> clazz, Constructor<?> constructor, Object[] arguments) throws Exception { if (clazz.getName().equals("com.google.gwt.user.client.ui.Tree")) { String signature = ReflectionUtils.getConstructorSignature(constructor); if (signature.equals("<init>(com.google.gwt.user.client.ui.TreeImages)")) { if (arguments[0] == null) { arguments[0] = ScriptUtils.evaluate(clazz.getClassLoader(), CodeUtils.getSource("import com.google.gwt.core.client.GWT;", "import com.google.gwt.user.client.ui.*;", "return GWT.create(TreeImages);")); } } } // prevent "null" as "cell" in CellList if (clazz.getName().equals("com.google.gwt.user.cellview.client.CellList")) { String signature = ReflectionUtils.getConstructorSignature(constructor); if (signature.equals("<init>(com.google.gwt.cell.client.Cell)")) { if (arguments[0] == null) { ClassLoader classLoader = clazz.getClassLoader(); Class<?> classTextCell = classLoader.loadClass("com.google.gwt.cell.client.TextCell"); arguments[0] = classTextCell.newInstance(); } } } }
From source file:com.streamsets.datacollector.definition.StageDefinitionExtractor.java
public List<ErrorMessage> validate(StageLibraryDefinition libraryDef, Class<? extends Stage> klass, Object contextMsg) {/*from www. j ava 2 s . c o m*/ List<ErrorMessage> errors = new ArrayList<>(); contextMsg = Utils.formatL("{} Stage='{}'", contextMsg, klass.getSimpleName()); StageDef sDef = klass.getAnnotation(StageDef.class); if (sDef == null) { errors.add(new ErrorMessage(DefinitionError.DEF_300, contextMsg)); } else { if (!sDef.icon().isEmpty()) { if (klass.getClassLoader().getResource(sDef.icon()) == null) { errors.add(new ErrorMessage(DefinitionError.DEF_311, contextMsg, sDef.icon())); } } StageType type = extractStageType(klass); if (type == null) { errors.add(new ErrorMessage(DefinitionError.DEF_302, contextMsg)); } boolean errorStage = klass.getAnnotation(ErrorStage.class) != null; if (type != null && errorStage && type == StageType.SOURCE) { errors.add(new ErrorMessage(DefinitionError.DEF_303, contextMsg)); } if (OffsetCommitTrigger.class.isAssignableFrom(klass) && type != StageType.TARGET) { errors.add(new ErrorMessage(DefinitionError.DEF_312, contextMsg)); } HideConfigs hideConfigs = klass.getAnnotation(HideConfigs.class); List<String> stageGroups = getGroups(klass); List<ErrorMessage> configGroupErrors = ConfigGroupExtractor.get().validate(klass, contextMsg); errors.addAll(configGroupErrors); errors.addAll(ConfigGroupExtractor.get().validate(klass, contextMsg)); List<ErrorMessage> configErrors = ConfigDefinitionExtractor.get().validate(klass, stageGroups, contextMsg); errors.addAll(configErrors); List<ErrorMessage> rawSourceErrors = RawSourceDefinitionExtractor.get().validate(klass, contextMsg); errors.addAll(rawSourceErrors); if (type != null && rawSourceErrors.isEmpty() && type != StageType.SOURCE) { if (RawSourceDefinitionExtractor.get().extract(klass, contextMsg) != null) { errors.add(new ErrorMessage(DefinitionError.DEF_304, contextMsg)); } } if (!sDef.outputStreams().isEnum()) { errors.add(new ErrorMessage(DefinitionError.DEF_305, contextMsg, sDef.outputStreams().getSimpleName())); } if (type != null && sDef.outputStreams() != StageDef.DefaultOutputStreams.class && type == StageType.TARGET) { errors.add(new ErrorMessage(DefinitionError.DEF_306, contextMsg)); } boolean variableOutputStreams = StageDef.VariableOutputStreams.class .isAssignableFrom(sDef.outputStreams()); List<ExecutionMode> executionModes = ImmutableList.copyOf(sDef.execution()); if (executionModes.isEmpty()) { errors.add(new ErrorMessage(DefinitionError.DEF_307, contextMsg)); } String outputStreamsDrivenByConfig = sDef.outputStreamsDrivenByConfig(); if (variableOutputStreams && outputStreamsDrivenByConfig.isEmpty()) { errors.add(new ErrorMessage(DefinitionError.DEF_308, contextMsg)); } if (configErrors.isEmpty() && configGroupErrors.isEmpty()) { List<ConfigDefinition> configDefs = extractConfigDefinitions(libraryDef, klass, hideConfigs, contextMsg); ConfigGroupDefinition configGroupDef = ConfigGroupExtractor.get().extract(klass, contextMsg); errors.addAll(validateConfigGroups(configDefs, configGroupDef, contextMsg)); if (variableOutputStreams) { boolean found = false; for (ConfigDefinition configDef : configDefs) { if (configDef.getName().equals(outputStreamsDrivenByConfig)) { found = true; break; } } if (!found) { errors.add( new ErrorMessage(DefinitionError.DEF_309, contextMsg, outputStreamsDrivenByConfig)); } } } } return errors; }
From source file:org.covito.kit.utility.ClassUtil.java
public static URL getClassLocation(final String clsName) { if (clsName == null) { return null; }//from w w w . j ava 2 s .c o m Class cls = null; try { cls = Class.forName(clsName); } catch (Exception e) { return null; } URL result = null; final String clsAsResource = cls.getName().replace('.', '/').concat(".class"); final ProtectionDomain pd = cls.getProtectionDomain(); // java.lang.Class contract does not specify if 'pd' can ever be null; // it is not the case for Sun's implementations, but guard against null // just in case: if (pd != null) { final CodeSource cs = pd.getCodeSource(); // 'cs' can be null depending on the classloader behavior: if (cs != null) result = cs.getLocation(); if (result != null) { // Convert a code source location into a full class file // location // for some common cases: 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) { // Try to find 'cls' definition as a resource; this is not // documentd to be legal, but Sun's implementations seem to //allow // this: final ClassLoader clsLoader = cls.getClassLoader(); result = clsLoader != null ? clsLoader.getResource(clsAsResource) : ClassLoader.getSystemResource(clsAsResource); } return result; }
From source file:hudson.model.Descriptor.java
protected final String getViewPage(Class<?> clazz, String pageName) { while (clazz != Object.class) { String name = clazz.getName().replace('.', '/').replace('$', '/') + "/" + pageName; if (clazz.getClassLoader().getResource(name) != null) return '/' + name; clazz = clazz.getSuperclass();// w ww . ja v a 2 s . c om } // We didn't find the configuration page. // Either this is non-fatal, in which case it doesn't matter what string we return so long as // it doesn't exist. // Or this error is fatal, in which case we want the developer to see what page he's missing. // so we put the page name. return pageName; }
From source file:com.github.hrpc.rpc.WritableRpcEngine.java
/** Construct a client-side proxy object that implements the named protocol, * talking to a server at the named address. * @param <T>*//*from w w w .j ava 2 s .c om*/ @Override @SuppressWarnings("unchecked") public <T> ProtocolProxy<T> getProxy(Class<T> protocol, long clientVersion, InetSocketAddress addr, Option 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, conf, factory, rpcTimeout)); return new ProtocolProxy<T>(protocol, proxy); }
From source file:org.blocks4j.feature.toggle.factory.FeatureToggleFactory.java
private <T> T createFeatureProxy(String featureName, Class<? super T> commonInterface, T featureOn, T featureOff) {// w w w . ja va 2 s . co m this.validateParams(featureName, commonInterface, featureOn, featureOff); Feature<T> feature; if (this.allowProbabilisticFeatures) { feature = new ProbabilisticFeature<T>(); } else { feature = new Feature<T>(); } feature.setConfig(this.config); feature.setCommonsInterface(commonInterface); feature.setOn(featureOn); feature.setOff(featureOff); feature.setName(featureName); feature.init(); @SuppressWarnings("unchecked") T proxy = (T) Proxy.newProxyInstance(commonInterface.getClassLoader(), new Class[] { commonInterface }, feature); LOGGER.info(String.format("Feature [%s] initialized , Object for ON is [%s] and Object for OFF is [%s]", featureName, featureOn.getClass().getSimpleName(), featureOff.getClass().getSimpleName())); toggleList.add(feature); return proxy; }
From source file:hudson.model.Descriptor.java
private InputStream getHelpStream(Class c, String suffix) { Locale locale = Stapler.getCurrentRequest().getLocale(); String base = c.getName().replace('.', '/') + "/help" + suffix; ClassLoader cl = c.getClassLoader(); if (cl == null) return null; InputStream in;//from w ww . j a va2s . co m in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + '_' + locale.getVariant() + ".html"); if (in != null) return in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + '_' + locale.getCountry() + ".html"); if (in != null) return in; in = cl.getResourceAsStream(base + '_' + locale.getLanguage() + ".html"); if (in != null) return in; // default return cl.getResourceAsStream(base + ".html"); }