Search in sources :

Example 1 with WatchEventListener

use of org.hotswap.agent.watch.WatchEventListener in project HotswapAgent by HotswapProjects.

the class WeldPlugin method registerBeanDeplArchivePath.

/**
 * Register BeanDeploymentArchive's normalizedArchivePath to watcher. In case of new class, the class file is not known
 * to JVM hence no hotswap is called and therefore it must be handled by watcher.
 *
 * @param archivePath the archive path
 */
public synchronized void registerBeanDeplArchivePath(final String archivePath) {
    URL resource = null;
    try {
        resource = resourceNameToURL(archivePath);
        URI uri = resource.toURI();
        if (!IOUtils.isDirectoryURL(uri.toURL())) {
            LOGGER.trace("Unable to watch for new files. Archive '{}' is not directory.", archivePath);
            return;
        } else {
            LOGGER.info("Registering archive path '{}'", archivePath);
            watcher.addEventListener(appClassLoader, uri, new WatchEventListener() {

                @Override
                public void onEvent(WatchFileEvent event) {
                    if (event.isFile() && event.getURI().toString().endsWith(".class")) {
                        // check that the class is not loaded by the classloader yet (avoid duplicate reload)
                        String className;
                        try {
                            className = IOUtils.urlToClassName(event.getURI());
                        } catch (IOException e) {
                            LOGGER.trace("Watch event on resource '{}' skipped, probably Ok because of delete/create event sequence (compilation not finished yet).", e, event.getURI());
                            return;
                        }
                        if (!ClassLoaderHelper.isClassLoaded(appClassLoader, className) || isTestEnvironment) {
                            // refresh weld only for new classes
                            LOGGER.trace("Register reload command: {} ", className);
                            if (isBdaRegistered(appClassLoader, archivePath)) {
                                // TODO : Create proxy factory
                                scheduler.scheduleCommand(new BeanClassRefreshCommand(appClassLoader, archivePath, event), WAIT_ON_CREATE);
                            }
                        }
                    }
                }
            });
        }
        LOGGER.info("Registered  watch for path '{}' for changes.", resource);
    } catch (URISyntaxException e) {
        LOGGER.error("Unable to watch path '{}' for changes.", e, archivePath);
    } catch (Exception e) {
        LOGGER.warning("registerBeanDeplArchivePath() exception : {}", e.getMessage());
    }
}
Also used : WatchFileEvent(org.hotswap.agent.watch.WatchFileEvent) BeanClassRefreshCommand(org.hotswap.agent.plugin.weld.command.BeanClassRefreshCommand) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) WatchEventListener(org.hotswap.agent.watch.WatchEventListener) URI(java.net.URI) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) NotFoundException(org.hotswap.agent.javassist.NotFoundException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 2 with WatchEventListener

use of org.hotswap.agent.watch.WatchEventListener in project HotswapAgent by HotswapProjects.

the class Log4j2Plugin method init.

/**
 * Callback method from
 * org.apache.logging.log4j.core.LoggerContext.setConfiguration(Configuration)
 *
 * @param config the Log4j2 configuration object
 */
public void init(final Object config) {
    URI configURI = null;
    try {
        Class<?> configurationClass = appClassLoader.loadClass("org.apache.logging.log4j.core.config.Configuration");
        Class<?> configurationSourceClass = appClassLoader.loadClass("org.apache.logging.log4j.core.config.ConfigurationSource");
        Object configurationSource = configurationClass.getDeclaredMethod("getConfigurationSource").invoke(config);
        String url = (String) configurationSourceClass.getDeclaredMethod("getLocation").invoke(configurationSource);
        configURI = Paths.get(url).toUri();
        if (registeredURIs.contains(configURI)) {
            return;
        }
        final URI parentUri = Paths.get(configURI).getParent().toUri();
        LOGGER.debug("Watching '{}' URI for Log4j2 configuration changes.", configURI);
        registeredURIs.add(configURI);
        watcher.addEventListener(appClassLoader, parentUri, new WatchEventListener() {

            @Override
            public void onEvent(WatchFileEvent event) {
                if (event.getEventType() != FileEvent.DELETE && registeredURIs.contains(event.getURI())) {
                    reload(event.getURI());
                }
            }
        });
        if (!initialized) {
            LOGGER.info("Log4j2 plugin initialized.");
            initialized = true;
        }
    } catch (Exception e) {
        LOGGER.error("Exception initializing Log4j2 on uri {}.", e, configURI);
    }
}
Also used : WatchFileEvent(org.hotswap.agent.watch.WatchFileEvent) WatchEventListener(org.hotswap.agent.watch.WatchEventListener) URI(java.net.URI) CannotCompileException(org.hotswap.agent.javassist.CannotCompileException) NotFoundException(org.hotswap.agent.javassist.NotFoundException)

Example 3 with WatchEventListener

use of org.hotswap.agent.watch.WatchEventListener in project HotswapAgent by HotswapProjects.

the class LogbackPlugin method initLogback.

/**
 * Callback method from ch.qos.logback.core.joran.GenericConfigurator.
 *
 * @param configurator the configurator object
 * @param url          configuration file url
 */
public void initLogback(final Object configurator, final URL url) {
    try {
        final URI uri = url.toURI();
        // skip double registration on reload
        if (registeredURIs.contains(uri))
            return;
        LOGGER.debug("Watching '{}' URL for Logback configuration changes.", url);
        registeredURIs.add(uri);
        watcher.addEventListener(appClassLoader, uri, new WatchEventListener() {

            @Override
            public void onEvent(WatchFileEvent event) {
                if (event.getEventType() != FileEvent.DELETE)
                    reload(configurator, url);
            }
        });
    } catch (Exception e) {
        LOGGER.error("Exception initializing logback configurator {} on url {}.", e, configurator, url);
    }
}
Also used : WatchFileEvent(org.hotswap.agent.watch.WatchFileEvent) WatchEventListener(org.hotswap.agent.watch.WatchEventListener) URI(java.net.URI)

Example 4 with WatchEventListener

use of org.hotswap.agent.watch.WatchEventListener in project HotswapAgent by HotswapProjects.

the class WatcherNIO2Test method createFile.

@Test
public void createFile() throws IOException {
    final ResultHolder resultHolder = new ResultHolder();
    watcher.addEventListener(null, temp.toUri(), new WatchEventListener() {

        @Override
        public void onEvent(WatchFileEvent event) {
            assertEquals("New file event type", FileEvent.CREATE, event.getEventType());
            assertTrue("File name", event.getURI().toString().endsWith("test.class"));
            resultHolder.result = true;
        }
    });
    File testFile = new File(temp.toFile(), "test.class");
    testFile.createNewFile();
    assertTrue("Event listener called", waitForResult(resultHolder));
}
Also used : WatchFileEvent(org.hotswap.agent.watch.WatchFileEvent) WatchEventListener(org.hotswap.agent.watch.WatchEventListener) File(java.io.File) Test(org.junit.Test)

Example 5 with WatchEventListener

use of org.hotswap.agent.watch.WatchEventListener in project HotswapAgent by HotswapProjects.

the class AbstractNIO2Watcher method closeClassLoader.

/**
 * Remove all transformers registered with a classloader
 *
 * @param classLoader
 */
@Override
public void closeClassLoader(ClassLoader classLoader) {
    for (Iterator<Entry<WatchEventListener, ClassLoader>> entryIterator = classLoaderListeners.entrySet().iterator(); entryIterator.hasNext(); ) {
        Entry<WatchEventListener, ClassLoader> entry = entryIterator.next();
        if (entry.getValue().equals(classLoader)) {
            entryIterator.remove();
            try {
                for (Iterator<Entry<Path, List<WatchEventListener>>> listenersIterator = listeners.entrySet().iterator(); listenersIterator.hasNext(); ) {
                    Entry<Path, List<WatchEventListener>> pathListenerEntry = listenersIterator.next();
                    List<WatchEventListener> l = pathListenerEntry.getValue();
                    if (l != null) {
                        l.remove(entry.getKey());
                    }
                    if (l == null || l.isEmpty()) {
                        listenersIterator.remove();
                    }
                }
            } catch (Exception e) {
                LOGGER.error("Ooops", e);
            }
        }
    }
    // cleanup...
    if (classLoaderListeners.isEmpty()) {
        listeners.clear();
        for (WatchKey wk : keys.keySet()) {
            try {
                wk.cancel();
            } catch (Exception e) {
                LOGGER.error("Ooops", e);
            }
        }
        try {
            this.watcher.close();
        } catch (IOException e) {
            LOGGER.error("Ooops", e);
        }
        LOGGER.info("All classloaders closed, released watch service..");
        try {
            // Reset
            this.watcher = FileSystems.getDefault().newWatchService();
        } catch (IOException e) {
            LOGGER.error("Ooops", e);
        }
    }
    LOGGER.debug("All watch listeners removed for classLoader {}", classLoader);
}
Also used : Path(java.nio.file.Path) WatchKey(java.nio.file.WatchKey) IOException(java.io.IOException) WatchEventListener(org.hotswap.agent.watch.WatchEventListener) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Entry(java.util.Map.Entry) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

WatchEventListener (org.hotswap.agent.watch.WatchEventListener)10 WatchFileEvent (org.hotswap.agent.watch.WatchFileEvent)8 IOException (java.io.IOException)5 URI (java.net.URI)5 File (java.io.File)3 URISyntaxException (java.net.URISyntaxException)3 URL (java.net.URL)3 NotFoundException (org.hotswap.agent.javassist.NotFoundException)3 MalformedURLException (java.net.MalformedURLException)2 Path (java.nio.file.Path)1 WatchKey (java.nio.file.WatchKey)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Entry (java.util.Map.Entry)1 Set (java.util.Set)1 CannotCompileException (org.hotswap.agent.javassist.CannotCompileException)1 BeanClassRefreshCommand (org.hotswap.agent.plugin.owb.command.BeanClassRefreshCommand)1 BeanClassRefreshCommand (org.hotswap.agent.plugin.weld.command.BeanClassRefreshCommand)1 Test (org.junit.Test)1