List of usage examples for java.net URLClassLoader close
public void close() throws IOException
From source file:net.pms.external.ExternalFactory.java
/** * This method loads the jar files found in the plugin dir * or if installed from the web.//w ww .j a v a 2 s . c om */ public static void loadJAR(URL[] jarURL, boolean download, URL newURL) { /* Create a classloader to take care of loading the plugin classes from * their URL. * * A not on the suppressed warning: The classloader need to remain open as long * as the loaded classes are in use - in our case forever. * @see http://stackoverflow.com/questions/13944868/leaving-classloader-open-after-first-use */ @SuppressWarnings("resource") URLClassLoader classLoader = new URLClassLoader(jarURL); Enumeration<URL> resources; try { // Each plugin .jar file has to contain a resource named "plugin" // which should contain the name of the main plugin class. resources = classLoader.getResources("plugin"); } catch (IOException e) { LOGGER.error("Can't load plugin resources: {}", e.getMessage()); LOGGER.trace("", e); try { classLoader.close(); } catch (IOException e2) { // Just swallow } return; } while (resources.hasMoreElements()) { URL url = resources.nextElement(); try { // Determine the plugin main class name from the contents of // the plugin file. char[] name; try (InputStreamReader in = new InputStreamReader(url.openStream())) { name = new char[512]; in.read(name); } String pluginMainClassName = new String(name).trim(); LOGGER.info("Found plugin: " + pluginMainClassName); if (download) { // Only purge code when downloading! purgeCode(pluginMainClassName, newURL); } // Try to load the class based on the main class name Class<?> clazz = classLoader.loadClass(pluginMainClassName); registerListenerClass(clazz); if (download) { downloadedListenerClasses.add(clazz); } } catch (Exception | NoClassDefFoundError e) { LOGGER.error("Error loading plugin", e); } } }
From source file:com.xiovr.unibot.plugin.impl.PluginLoaderImpl.java
@Override public void unloadPlugin(Class<?> _class) { try {/*from w w w .j a va 2s . c om*/ URLClassLoader cl = (URLClassLoader) _class.getClass().getClassLoader(); cl.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.temenos.interaction.loader.classloader.CachingParentLastURLClassloaderFactory.java
private void cleanupClassloaderResources(URLClassLoader previousCL, File previousTempDir) { try {/*from ww w .j a va 2 s .c o m*/ if (previousCL != null) { previousCL.close(); } } catch (IOException ex) { LOGGER.error("Failed to close classloader - potential resource and memory leak!", ex); } try { if (previousTempDir != null) { FileUtils.forceDelete(previousTempDir); } } catch (IOException ex) { LOGGER.error("Failed to delete temporary directory, possible resource leak!", ex); } }
From source file:com.heimuheimu.runningtask.task.service.support.SimpleTaskExecutor.java
private synchronized void closeClassLoader(URLClassLoader targetClassLoader) { if (targetClassLoader != null) { long startTime = System.currentTimeMillis(); try {/*from w ww. j a v a 2s .c o m*/ targetClassLoader.close(); LOG.info("Close url class loader success. Cost: `{}ms`. Urls: `{}`", System.currentTimeMillis() - startTime, Arrays.toString(targetClassLoader.getURLs())); } catch (Exception e) { LOG.error("Close url class loader fail. It may be lead to memory leak. Urls: `" + Arrays.toString(targetClassLoader.getURLs()) + "`", e); } } }
From source file:de.xaniox.heavyspleef.addon.AddOnManager.java
public void unloadAddOn(String name) { Validate.isTrue(addOnMap.containsKey(name)); AddOn addOn = addOnMap.remove(name); if (addOn.isEnabled()) { addOn.disable();/*from www. j a v a 2 s . com*/ } BasicAddOn basicAddOn = (BasicAddOn) addOn; URLClassLoader classLoader = (URLClassLoader) basicAddOn.getClassLoader(); try { classLoader.close(); } catch (IOException e) { logger.log(Level.SEVERE, "Could not properly close the classloader of add-on " + addOn.getName(), e); } if (addOn.getProperties().getLoadingMode() != null) { //Unregister i18n I18NManager i18nManager = heavySpleef.getI18NManager(); i18nManager.unregisterI18N(basicAddOn.getName()); } CommandManagerService service = heavySpleef.getCommandManager().getService(); service.removeArgument(addOn); //Clear class cache classContext.unregister(addOn); }
From source file:net.pms.external.ExternalFactory.java
private static String getMainClass(URL jar) { URL[] jarURLs1 = { jar };// ww w. jav a2 s . c o m URLClassLoader classLoader = new URLClassLoader(jarURLs1); try { Enumeration<URL> resources; try { // Each plugin .jar file has to contain a resource named "plugin" // which should contain the name of the main plugin class. resources = classLoader.getResources("plugin"); if (resources.hasMoreElements()) { URL url = resources.nextElement(); char[] name; // Determine the plugin main class name from the contents of // the plugin file. try (InputStreamReader in = new InputStreamReader(url.openStream())) { name = new char[512]; in.read(name); } return new String(name).trim(); } } catch (IOException e) { LOGGER.error("Can't load plugin resources", e); } } finally { try { classLoader.close(); } catch (IOException e) { LOGGER.error("Error closing plugin finder: {}", e.getMessage()); LOGGER.trace("", e); } } return null; }
From source file:hydrograph.ui.expression.editor.buttons.ValidateExpressionToolButton.java
/** * Complies the given expression using engine's jar from ELT-Project's build path. * //from w w w. jav a2 s . c om * @param expressionStyledText * @param fieldMap * @param componentName * @return DiagnosticCollector * complete diagnosis of given expression * @throws JavaModelException * @throws InvocationTargetException * @throws ClassNotFoundException * @throws MalformedURLException * @throws IllegalAccessException * @throws IllegalArgumentException */ @SuppressWarnings({ "unchecked" }) public static DiagnosticCollector<JavaFileObject> compileExpresion(String expressionStyledText, Map<String, Class<?>> fieldMap, String componentName) throws JavaModelException, InvocationTargetException, ClassNotFoundException, MalformedURLException, IllegalAccessException, IllegalArgumentException { LOGGER.debug("Compiling expression using Java-Compiler"); String expressiontext = getExpressionText(expressionStyledText); DiagnosticCollector<JavaFileObject> diagnostics = null; Object[] returObj = getBuildPathForMethodInvocation(); List<URL> urlList = (List<URL>) returObj[0]; String transfromJarPath = (String) returObj[1]; String propertyFilePath = (String) returObj[2]; URLClassLoader child = URLClassLoader.newInstance(urlList.toArray(new URL[urlList.size()])); Class<?> class1 = Class.forName(HYDROGRAPH_ENGINE_EXPRESSION_VALIDATION_API_CLASS, true, child); Thread.currentThread().setContextClassLoader(child); Method[] methods = class1.getDeclaredMethods(); for (Method method : methods) { if (method.getParameterTypes().length == 4 && StringUtils.equals(method.getName(), COMPILE_METHOD_OF_EXPRESSION_JAR_FOR_TRANSFORM_COMPONENTS) && !StringUtils.equalsIgnoreCase(componentName, hydrograph.ui.common.util.Constants.FILTER)) { method.getDeclaringClass().getClassLoader(); diagnostics = (DiagnosticCollector<JavaFileObject>) method.invoke(null, expressiontext, propertyFilePath, fieldMap, transfromJarPath); break; } else if (method.getParameterTypes().length == 4 && StringUtils.equals(method.getName(), COMPILE_METHOD_OF_EXPRESSION_JAR_FOR_FILTER_COMPONENT) && StringUtils.equalsIgnoreCase(componentName, hydrograph.ui.common.util.Constants.FILTER)) { method.getDeclaringClass().getClassLoader(); diagnostics = (DiagnosticCollector<JavaFileObject>) method.invoke(null, expressiontext, propertyFilePath, fieldMap, transfromJarPath); break; } } try { child.close(); } catch (IOException ioException) { LOGGER.error("Error occurred while closing classloader", ioException); } return diagnostics; }
From source file:org.bigtester.ate.model.caserunner.CaseRunnerGenerator.java
private void loadClass(String classFilePathName, String className) throws ClassNotFoundException, IOException { /** Compilation Requirements *********************************************************************************************/ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = getCompiler().getStandardFileManager(diagnostics, null, null); // This sets up the class path that the compiler will use. // I've added the .jar file that contains the DoStuff interface within // in it.../*from w ww .ja va 2s . c o m*/ List<String> optionList = new ArrayList<String>(); optionList.add("-classpath"); optionList.add(getAllJarsClassPathInMavenLocalRepo()); optionList.add("-verbose"); File helloWorldJava = new File(classFilePathName); Iterable<? extends JavaFileObject> compilationUnit = fileManager .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava)); JavaCompiler.CompilationTask task = getCompiler().getTask(null, fileManager, diagnostics, optionList, null, compilationUnit); /********************************************************************************************* Compilation Requirements **/ if (task.call()) { /** Load and execute *************************************************************************************************/ // Create a new custom class loader, pointing to the directory that // contains the compiled // classes, this should point to the top of the package structure! //TODO the / separator needs to be revised to platform awared URLClassLoader classLoader = new URLClassLoader(new URL[] { new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() }, Thread.currentThread().getContextClassLoader()); String addonClasspath = System.getProperty("user.dir") + "/generated-code/caserunners/"; ClassLoaderUtil.addFileToClassPath(addonClasspath, classLoader.getParent()); classLoader.loadClass(className); classLoader.close(); /************************************************************************************************* Load and execute **/ } else { for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { System.out.format("Error on line %d in %s%n with error %s", diagnostic.getLineNumber(), diagnostic.getSource(), diagnostic.getMessage(new Locale("en"))); } } }
From source file:com.zimbra.cs.zimlet.ZimletUtil.java
/** * Loads all the Zimlets, locates the server side ZimletHandler for each Zimlets, * loads the class and instantiate the object, then returns the instance. * * @param name of the Zimlet/*from ww w . j a v a 2 s. c o m*/ * @return ZimletHandler object */ public static ZimletHandler getHandler(String name) { loadZimlets(); Class zh = sZimletHandlers.get(name); if (zh == null) { ZimletFile zf = sZimlets.get(name); if (zf == null) { return null; } URLClassLoader cl = null; try { String clazz = zf.getZimletDescription().getServerExtensionClass(); if (clazz != null) { URL[] urls = { zf.toURL() }; cl = new URLClassLoader(urls, ZimletUtil.class.getClassLoader()); zh = cl.loadClass(clazz); ZimbraLog.zimlet.info("Loaded class " + zh.getName()); sZimletHandlers.put(name, zh); } } catch (Exception e) { ZimbraLog.zimlet.warn("Unable to load zimlet handler for %s", name, e); return null; } finally { if (cl != null) { try { cl.close(); } catch (IOException e) { ZimbraLog.zimlet.warn("failed to close URLClassLoader", e); } } } } try { if (zh != null) { return (ZimletHandler) zh.newInstance(); } } catch (Exception e) { ZimbraLog.zimlet.warn("Unable to instantiate zimlet handler for " + name, e); } return null; }
From source file:io.syndesis.maven.ExtractConnectorDescriptorsMojo.java
@Override @SuppressWarnings("PMD.EmptyCatchBlock") public void execute() throws MojoExecutionException, MojoFailureException { ArrayNode root = new ArrayNode(JsonNodeFactory.instance); URLClassLoader classLoader = null; try {//from w w w . j a va 2 s. c o m PluginDescriptor desc = (PluginDescriptor) getPluginContext().get("pluginDescriptor"); List<Artifact> artifacts = desc.getArtifacts(); ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest( session.getProjectBuildingRequest()); buildingRequest.setRemoteRepositories(remoteRepositories); for (Artifact artifact : artifacts) { ArtifactResult result = artifactResolver.resolveArtifact(buildingRequest, artifact); File jar = result.getArtifact().getFile(); classLoader = createClassLoader(jar); if (classLoader == null) { throw new IOException("Can not create classloader for " + jar); } ObjectNode entry = new ObjectNode(JsonNodeFactory.instance); addConnectorMeta(entry, classLoader); addComponentMeta(entry, classLoader); if (entry.size() > 0) { addGav(entry, artifact); root.add(entry); } } if (root.size() > 0) { saveCamelMetaData(root); } } catch (ArtifactResolverException | IOException e) { throw new MojoExecutionException(e.getMessage(), e); } finally { if (classLoader != null) { try { classLoader.close(); } catch (IOException ignored) { } } } }