Search in sources :

Example 21 with ResourceChange

use of org.apache.sling.api.resource.observation.ResourceChange in project sling by apache.

the class DistributingEventHandlerTest method setup.

@SuppressWarnings("unchecked")
@Before
public void setup() throws Exception {
    final BundleContext bc = Mockito.mock(BundleContext.class);
    Mockito.when(bc.registerService(Mockito.any(String[].class), Mockito.any(), Mockito.any(Dictionary.class))).thenReturn(null);
    final SlingSettingsService otherSettings = Mockito.mock(SlingSettingsService.class);
    Mockito.when(otherSettings.getSlingId()).thenReturn(OTHER_APP_ID);
    final EventAdmin ea = new EventAdmin() {

        @Override
        public void sendEvent(final Event event) {
            this.postEvent(event);
        }

        @Override
        public void postEvent(final Event event) {
            final String topic = event.getTopic();
            if (topic.equals(SlingConstants.TOPIC_RESOURCE_ADDED)) {
                final ResourceChange change = new ResourceChange(ChangeType.ADDED, (String) event.getProperty(SlingConstants.PROPERTY_PATH), false, null, null, null);
                sender.onChange(Collections.singletonList(change));
            } else if (topic.startsWith(TOPIC_PREFIX)) {
                events.add(event);
            }
        }
    };
    final MockResourceResolverFactoryOptions opts = new MockResourceResolverFactoryOptions();
    opts.setEventAdmin(ea);
    final ResourceResolverFactory factory = new MockResourceResolverFactory(opts);
    this.sender = new DistributedEventSender(bc, DistributedEventAdminImpl.DEFAULT_REPOSITORY_PATH, DistributedEventAdminImpl.DEFAULT_REPOSITORY_PATH + "/" + MY_APP_ID, factory, ea);
    this.receiver = new DistributedEventReceiver(bc, DistributedEventAdminImpl.DEFAULT_REPOSITORY_PATH, DistributedEventAdminImpl.DEFAULT_REPOSITORY_PATH + "/" + OTHER_APP_ID, 15, factory, otherSettings);
}
Also used : Dictionary(java.util.Dictionary) ResourceResolverFactory(org.apache.sling.api.resource.ResourceResolverFactory) MockResourceResolverFactory(org.apache.sling.testing.resourceresolver.MockResourceResolverFactory) EventAdmin(org.osgi.service.event.EventAdmin) MockResourceResolverFactoryOptions(org.apache.sling.testing.resourceresolver.MockResourceResolverFactoryOptions) Event(org.osgi.service.event.Event) MockResourceResolverFactory(org.apache.sling.testing.resourceresolver.MockResourceResolverFactory) ResourceChange(org.apache.sling.api.resource.observation.ResourceChange) SlingSettingsService(org.apache.sling.settings.SlingSettingsService) BundleContext(org.osgi.framework.BundleContext) Before(org.junit.Before)

Example 22 with ResourceChange

use of org.apache.sling.api.resource.observation.ResourceChange in project sling by apache.

the class JcrResourceBundleProvider method onChange.

// ---------- EventHandler ------------------------------------------------
@Override
public void onChange(List<ResourceChange> changes) {
    boolean refreshed = false;
    for (final ResourceChange change : changes) {
        log.trace("handleEvent: Detecting event {} for path '{}'", change.getType(), change.getPath());
        // invalidate everything
        if (languageRootPaths.contains(change.getPath())) {
            log.debug("handleEvent: Detected change of cached language root '{}', removing all cached ResourceBundles", change.getPath());
            scheduleReloadBundles(true);
        } else {
            // if it is only a change below a root path, only messages of one resource bundle can be affected!
            for (final String root : languageRootPaths) {
                if (change.getPath().startsWith(root)) {
                    // figure out which JcrResourceBundle from the cached ones is affected
                    for (JcrResourceBundle bundle : resourceBundleCache.values()) {
                        if (bundle.getLanguageRootPaths().contains(root)) {
                            // reload it
                            log.debug("handleEvent: Resource changes below '{}', reloading ResourceBundle '{}'", root, bundle);
                            scheduleReloadBundle(bundle);
                            return;
                        }
                    }
                    log.debug("handleEvent: No cached resource bundle found with root '{}'", root);
                    break;
                }
            }
            // may be a completely new dictionary
            if (!refreshed) {
                // refresh at most once per onChange()
                resourceResolver.refresh();
                refreshed = true;
            }
            if (isDictionaryResource(change)) {
                scheduleReloadBundles(true);
            }
        }
    }
}
Also used : ResourceChange(org.apache.sling.api.resource.observation.ResourceChange)

Example 23 with ResourceChange

use of org.apache.sling.api.resource.observation.ResourceChange in project sling by apache.

the class JcrResourceListenerTest method testMultiplePaths.

@Test
public void testMultiplePaths() throws Exception {
    ObserverConfiguration observerConfig = new ObserverConfiguration() {

        @Override
        public boolean includeExternal() {
            return true;
        }

        @Override
        public PathSet getPaths() {
            return PathSet.fromStrings("/libs", "/apps");
        }

        @Override
        public PathSet getExcludedPaths() {
            return PathSet.fromPaths();
        }

        @Override
        public Set<ChangeType> getChangeTypes() {
            return EnumSet.allOf(ChangeType.class);
        }

        @Override
        public boolean matches(String path) {
            return this.getPaths().matches(path) != null;
        }

        @Override
        public Set<String> getPropertyNamesHint() {
            return null;
        }
    };
    this.config.unregister(this.listener);
    this.listener = null;
    final Session session = this.adminSession;
    if (!session.nodeExists("/libs")) {
        createNode(session, "/libs");
    }
    if (!session.nodeExists("/apps")) {
        createNode(session, "/apps");
    }
    session.getNode("/libs").addNode("foo" + System.currentTimeMillis());
    session.getNode("/apps").addNode("foo" + System.currentTimeMillis());
    session.save();
    Thread.sleep(200);
    this.events.clear();
    try (final JcrResourceListener l = new JcrResourceListener(this.config, observerConfig)) {
        final String rootName = "test_" + System.currentTimeMillis();
        for (final String path : new String[] { "/libs", "/", "/apps", "/content" }) {
            final Node parent;
            if (!session.nodeExists(path)) {
                parent = createNode(session, path);
            } else {
                parent = session.getNode(path);
            }
            final Node node = parent.addNode(rootName, "nt:unstructured");
            session.save();
            node.setProperty("foo", "bar");
            session.save();
            node.remove();
            session.save();
        }
        assertEquals("Received: " + events, 6, events.size());
        final Set<String> addPaths = new HashSet<String>();
        final Set<String> modifyPaths = new HashSet<String>();
        final Set<String> removePaths = new HashSet<String>();
        for (final ResourceChange event : events) {
            if (event.getType() == ChangeType.ADDED) {
                addPaths.add(event.getPath());
            } else if (event.getType() == ChangeType.CHANGED) {
                modifyPaths.add(event.getPath());
            } else if (event.getType() == ChangeType.REMOVED) {
                removePaths.add(event.getPath());
            } else {
                fail("Unexpected event: " + event);
            }
            assertNotNull(event.getUserId());
        }
        assertEquals("Received: " + addPaths, 2, addPaths.size());
        assertTrue("Added set should contain /libs/" + rootName, addPaths.contains("/libs/" + rootName));
        assertTrue("Added set should contain /apps/" + rootName, addPaths.contains("/apps/" + rootName));
        assertEquals("Received: " + modifyPaths, 2, modifyPaths.size());
        assertTrue("Modified set should contain /libs/" + rootName, modifyPaths.contains("/libs/" + rootName));
        assertTrue("Modified set should contain /apps/" + rootName, modifyPaths.contains("/apps/" + rootName));
        assertEquals("Received: " + removePaths, 2, removePaths.size());
        assertTrue("Removed set should contain /libs/" + rootName, removePaths.contains("/libs/" + rootName));
        assertTrue("Removed set should contain /apps/" + rootName, removePaths.contains("/apps/" + rootName));
    }
}
Also used : ChangeType(org.apache.sling.api.resource.observation.ResourceChange.ChangeType) Node(javax.jcr.Node) ObserverConfiguration(org.apache.sling.spi.resource.provider.ObserverConfiguration) ResourceChange(org.apache.sling.api.resource.observation.ResourceChange) Session(javax.jcr.Session) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 24 with ResourceChange

use of org.apache.sling.api.resource.observation.ResourceChange in project sling by apache.

the class JcrResourceListenerTest method testSimpleOperations.

@Test
public void testSimpleOperations() throws Exception {
    generateEvents();
    assertEquals("Received: " + events, 5, events.size());
    final Set<String> addPaths = new HashSet<String>();
    final Set<String> modifyPaths = new HashSet<String>();
    final Set<String> removePaths = new HashSet<String>();
    for (final ResourceChange event : events) {
        if (event.getType() == ChangeType.ADDED) {
            addPaths.add(event.getPath());
        } else if (event.getType() == ChangeType.CHANGED) {
            modifyPaths.add(event.getPath());
        } else if (event.getType() == ChangeType.REMOVED) {
            removePaths.add(event.getPath());
        } else {
            fail("Unexpected event: " + event);
        }
        assertNotNull(event.getUserId());
    }
    assertEquals(3, addPaths.size());
    assertTrue("Added set should contain " + createdPath, addPaths.contains(createdPath));
    assertTrue("Added set should contain " + pathToDelete, addPaths.contains(pathToDelete));
    assertTrue("Added set should contain " + pathToModify, addPaths.contains(pathToModify));
    assertEquals(1, modifyPaths.size());
    assertTrue("Modified set should contain " + pathToModify, modifyPaths.contains(pathToModify));
    assertEquals(1, removePaths.size());
    assertTrue("Removed set should contain " + pathToDelete, removePaths.contains(pathToDelete));
}
Also used : ResourceChange(org.apache.sling.api.resource.observation.ResourceChange) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 25 with ResourceChange

use of org.apache.sling.api.resource.observation.ResourceChange in project sling by apache.

the class FileMonitorTest method testUpdateContent.

@Test
public void testUpdateContent() throws Exception {
    List<ResourceChange> changes = resourceListener.getChanges();
    assertTrue(changes.isEmpty());
    File file1a = new File(tempDir, "folder2/content.json");
    FileUtils.touch(file1a);
    Thread.sleep(WAIT_INTERVAL);
    assertChange(changes, "/fs-test/folder2/content", ChangeType.REMOVED);
    assertChange(changes, "/fs-test/folder2/content", ChangeType.ADDED);
    assertChange(changes, "/fs-test/folder2/content/jcr:content", ChangeType.ADDED);
}
Also used : ResourceChange(org.apache.sling.api.resource.observation.ResourceChange) File(java.io.File) Test(org.junit.Test)

Aggregations

ResourceChange (org.apache.sling.api.resource.observation.ResourceChange)38 Test (org.junit.Test)20 File (java.io.File)17 HashSet (java.util.HashSet)4 ArrayList (java.util.ArrayList)3 Event (org.osgi.service.event.Event)2 ImmutableList (com.google.common.collect.ImmutableList)1 SoftReference (java.lang.ref.SoftReference)1 Dictionary (java.util.Dictionary)1 HashMap (java.util.HashMap)1 Hashtable (java.util.Hashtable)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Map (java.util.Map)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 Node (javax.jcr.Node)1 RepositoryException (javax.jcr.RepositoryException)1 Session (javax.jcr.Session)1 Event (javax.jcr.observation.Event)1 JackrabbitEvent (org.apache.jackrabbit.api.observation.JackrabbitEvent)1