Search in sources :

Example 1 with WatchFileEvent

use of org.hotswap.agent.watch.WatchFileEvent 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 WatchFileEvent

use of org.hotswap.agent.watch.WatchFileEvent 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 WatchFileEvent

use of org.hotswap.agent.watch.WatchFileEvent 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 WatchFileEvent

use of org.hotswap.agent.watch.WatchFileEvent 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 WatchFileEvent

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

the class SpringPlugin method registerComponentScanBasePackage.

/**
 * Register both hotswap transformer AND watcher - in case of new file the file is not known
 * to JVM and hence no hotswap is called. The file may even exist, but until is loaded by Spring
 * it will not be known by the JVM. File events are processed only if the class is not known to the
 * classloader yet.
 *
 * @param basePackage only files in a basePackage
 */
public void registerComponentScanBasePackage(final String basePackage) {
    LOGGER.info("Registering basePackage {}", basePackage);
    this.registerBasePackage(basePackage);
    Enumeration<URL> resourceUrls = null;
    try {
        resourceUrls = getResources(basePackage);
    } catch (IOException e) {
        LOGGER.error("Unable to resolve base package {} in classloader {}.", basePackage, appClassLoader);
        return;
    }
    // for all application resources watch for changes
    while (resourceUrls.hasMoreElements()) {
        URL basePackageURL = resourceUrls.nextElement();
        if (!IOUtils.isFileURL(basePackageURL)) {
            LOGGER.debug("Spring basePackage '{}' - unable to watch files on URL '{}' for changes (JAR file?), limited hotswap reload support. " + "Use extraClassPath configuration to locate class file on filesystem.", basePackage, basePackageURL);
            continue;
        } else {
            watcher.addEventListener(appClassLoader, basePackageURL, 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)) {
                            // refresh spring only for new classes
                            scheduler.scheduleCommand(new ClassPathBeanRefreshCommand(appClassLoader, basePackage, className, event), WAIT_ON_CREATE);
                        }
                    }
                }
            });
        }
    }
}
Also used : WatchFileEvent(org.hotswap.agent.watch.WatchFileEvent) IOException(java.io.IOException) WatchEventListener(org.hotswap.agent.watch.WatchEventListener) URL(java.net.URL)

Aggregations

WatchEventListener (org.hotswap.agent.watch.WatchEventListener)8 WatchFileEvent (org.hotswap.agent.watch.WatchFileEvent)8 URI (java.net.URI)5 IOException (java.io.IOException)3 URL (java.net.URL)3 NotFoundException (org.hotswap.agent.javassist.NotFoundException)3 File (java.io.File)2 MalformedURLException (java.net.MalformedURLException)2 URISyntaxException (java.net.URISyntaxException)2 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