Search in sources :

Example 21 with ResourceResolverFactory

use of org.apache.sling.api.resource.ResourceResolverFactory in project sling by apache.

the class OakDiscoveryService method doUpdateProperties.

/**
     * Update the properties by inquiring the PropertyProvider's current values.
     * <p>
     * This method is invoked regularly by the heartbeatHandler.
     * The properties are stored in the repository under Config.getClusterInstancesPath()
     * and announced in the topology.
     * <p>
     * @see Config#getClusterInstancesPath()
     */
private void doUpdateProperties() {
    // SLING-5382 : the caller must ensure that this method
    // is not invoked after deactivation or before activation.
    // so this method doesn't have to do any further synchronization.
    // what we do nevertheless is a paranoia way of checking if
    // all variables are available and do a NOOP if that's not the case.
    final ResourceResolverFactory rrf = resourceResolverFactory;
    final Config c = config;
    final String sid = slingId;
    if (rrf == null || c == null || sid == null) {
        // cannot update the properties then..
        logger.debug("doUpdateProperties: too early to update the properties. " + "resourceResolverFactory ({}), config ({}) or slingId ({}) not yet set.", new Object[] { rrf, c, sid });
        return;
    } else {
        logger.debug("doUpdateProperties: updating properties now..");
    }
    final Map<String, String> newProps = new HashMap<String, String>();
    for (final ProviderInfo info : this.providerInfos) {
        info.refreshProperties();
        newProps.putAll(info.properties);
    }
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = rrf.getServiceResourceResolver(null);
        Resource myInstance = ResourceHelper.getOrCreateResource(resourceResolver, c.getClusterInstancesPath() + "/" + sid + "/properties");
        // SLING-2879 - revert/refresh resourceResolver here to work
        // around a potential issue with jackrabbit in a clustered environment
        resourceResolver.revert();
        resourceResolver.refresh();
        final ModifiableValueMap myInstanceMap = myInstance.adaptTo(ModifiableValueMap.class);
        final Set<String> keys = new HashSet<String>(myInstanceMap.keySet());
        for (final String key : keys) {
            if (newProps.containsKey(key)) {
                // perfect
                continue;
            } else if (key.indexOf(":") != -1) {
                // ignore
                continue;
            } else {
                // remove
                myInstanceMap.remove(key);
            }
        }
        boolean anyChanges = false;
        for (final Entry<String, String> entry : newProps.entrySet()) {
            Object existingValue = myInstanceMap.get(entry.getKey());
            if (entry.getValue().equals(existingValue)) {
                // SLING-3389: dont rewrite the properties if nothing changed!
                if (logger.isDebugEnabled()) {
                    logger.debug("doUpdateProperties: unchanged: {}={}", entry.getKey(), entry.getValue());
                }
                continue;
            }
            if (logger.isDebugEnabled()) {
                logger.debug("doUpdateProperties: changed: {}={}", entry.getKey(), entry.getValue());
            }
            anyChanges = true;
            myInstanceMap.put(entry.getKey(), entry.getValue());
        }
        if (anyChanges) {
            resourceResolver.commit();
        }
    } catch (LoginException e) {
        logger.error("handleEvent: could not log in administratively: " + e, e);
        throw new RuntimeException("Could not log in to repository (" + e + ")", e);
    } catch (PersistenceException e) {
        logger.error("handleEvent: got a PersistenceException: " + e, e);
        throw new RuntimeException("Exception while talking to repository (" + e + ")", e);
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
    logger.debug("doUpdateProperties: updating properties done.");
}
Also used : HashMap(java.util.HashMap) Resource(org.apache.sling.api.resource.Resource) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) ResourceResolverFactory(org.apache.sling.api.resource.ResourceResolverFactory) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException) HashSet(java.util.HashSet)

Example 22 with ResourceResolverFactory

use of org.apache.sling.api.resource.ResourceResolverFactory in project sling by apache.

the class OakDiscoveryServiceTest method testDescriptorSeqNumChange.

@Test
public void testDescriptorSeqNumChange() throws Exception {
    logger.info("testDescriptorSeqNumChange: start");
    OakVirtualInstanceBuilder builder1 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder().setDebugName("instance1").newRepository("/foo/barry/foo/", true).setConnectorPingInterval(999).setConnectorPingTimeout(999);
    VirtualInstance instance1 = builder1.build();
    OakVirtualInstanceBuilder builder2 = (OakVirtualInstanceBuilder) new OakVirtualInstanceBuilder().setDebugName("instance2").useRepositoryOf(instance1).setConnectorPingInterval(999).setConnectorPingTimeout(999);
    VirtualInstance instance2 = builder2.build();
    logger.info("testDescriptorSeqNumChange: created both instances, binding listener...");
    DummyListener listener = new DummyListener();
    OakDiscoveryService discoveryService = (OakDiscoveryService) instance1.getDiscoveryService();
    discoveryService.bindTopologyEventListener(listener);
    logger.info("testDescriptorSeqNumChange: waiting 2sec, listener should not get anything yet");
    assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
    assertEquals(0, listener.countEvents());
    logger.info("testDescriptorSeqNumChange: issuing 2 heartbeats with each instance should let the topology get established");
    instance1.heartbeatsAndCheckView();
    instance2.heartbeatsAndCheckView();
    instance1.heartbeatsAndCheckView();
    instance2.heartbeatsAndCheckView();
    logger.info("testDescriptorSeqNumChange: listener should get an event within 2sec from now at latest");
    assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
    assertEquals(1, listener.countEvents());
    ResourceResolverFactory factory = instance1.getResourceResolverFactory();
    ResourceResolver resolver = factory.getServiceResourceResolver(null);
    instance1.heartbeatsAndCheckView();
    assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
    assertEquals(1, listener.countEvents());
    // increment the seqNum by 2 - simulating a coming and going instance
    // while we were sleeping
    SimulatedLeaseCollection c = builder1.getSimulatedLeaseCollection();
    c.incSeqNum(2);
    logger.info("testDescriptorSeqNumChange: incremented seqnum by 2 - issuing another heartbeat should trigger a topology change");
    instance1.heartbeatsAndCheckView();
    // due to the nature of the syncService/minEventDelay we now explicitly first sleep 2sec before waiting for async events for another 2sec
    logger.info("testDescriptorSeqNumChange: sleeping 2sec for topology change to happen");
    Thread.sleep(2000);
    logger.info("testDescriptorSeqNumChange: ensuring no async events are still in the pipe - for another 2sec");
    assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
    logger.info("testDescriptorSeqNumChange: now listener should have received 3 events, it got: " + listener.countEvents());
    assertEquals(3, listener.countEvents());
}
Also used : OakVirtualInstanceBuilder(org.apache.sling.discovery.oak.its.setup.OakVirtualInstanceBuilder) SimulatedLeaseCollection(org.apache.sling.discovery.oak.its.setup.SimulatedLeaseCollection) ResourceResolverFactory(org.apache.sling.api.resource.ResourceResolverFactory) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) VirtualInstance(org.apache.sling.discovery.base.its.setup.VirtualInstance) DummyListener(org.apache.sling.discovery.commons.providers.base.DummyListener) Test(org.junit.Test)

Example 23 with ResourceResolverFactory

use of org.apache.sling.api.resource.ResourceResolverFactory in project sling by apache.

the class DiscoveryServiceImplTest method testLocalClusterSyncTokenIdChange.

@Test
public void testLocalClusterSyncTokenIdChange() throws Exception {
    logger.info("testLocalClusterSyncTokenIdChange: start");
    logger.info("testLocalClusterSyncTokenIdChange: creating instance1...");
    FullJR2VirtualInstanceBuilder builder1 = (FullJR2VirtualInstanceBuilder) new FullJR2VirtualInstanceBuilder().setDebugName("instance1").newRepository("/var/testLocalClusterSyncTokenIdChange/", true).setConnectorPingInterval(999).setConnectorPingTimeout(999).setMinEventDelay(0);
    VirtualInstance instance1 = builder1.build();
    logger.info("testLocalClusterSyncTokenIdChange: creating instance2...");
    FullJR2VirtualInstanceBuilder builder2 = (FullJR2VirtualInstanceBuilder) new FullJR2VirtualInstanceBuilder().setDebugName("instance2").useRepositoryOf(instance1).setConnectorPingInterval(999).setConnectorPingTimeout(999).setMinEventDelay(0);
    VirtualInstance instance2 = builder2.build();
    logger.info("testLocalClusterSyncTokenIdChange: registering listener...");
    DummyListener listener = new DummyListener();
    DiscoveryServiceImpl discoveryService = (DiscoveryServiceImpl) instance1.getDiscoveryService();
    discoveryService.bindTopologyEventListener(listener);
    assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
    assertEquals(0, listener.countEvents());
    logger.info("testLocalClusterSyncTokenIdChange: doing some heartbeating...");
    instance1.heartbeatsAndCheckView();
    instance2.heartbeatsAndCheckView();
    Thread.sleep(1000);
    instance1.heartbeatsAndCheckView();
    instance2.heartbeatsAndCheckView();
    Thread.sleep(2000);
    logger.info("testLocalClusterSyncTokenIdChange: expecting to have received the INIT...");
    assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
    assertEquals(1, listener.countEvents());
    ResourceResolverFactory factory = instance1.getResourceResolverFactory();
    ResourceResolver resolver = factory.getServiceResourceResolver(null);
    instance1.heartbeatsAndCheckView();
    instance2.heartbeatsAndCheckView();
    Thread.sleep(1000);
    logger.info("testLocalClusterSyncTokenIdChange: after another heartbeat nothing more should have been triggered...");
    assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
    assertEquals(1, listener.countEvents());
    // simulate a change in the establishedView's viewId - which can be
    // achieved by triggering a revoting - which should result with the
    // same view cos the instances have not changed
    HeartbeatHandler heartbeatHandler = (HeartbeatHandler) instance1.getViewChecker();
    logger.info("testLocalClusterSyncTokenIdChange: forcing a new voting to start...");
    heartbeatHandler.startNewVoting();
    logger.info("testLocalClusterSyncTokenIdChange: doing some heartbeats to finish the voting...");
    instance1.heartbeatsAndCheckView();
    instance2.heartbeatsAndCheckView();
    Thread.sleep(1000);
    instance1.heartbeatsAndCheckView();
    instance2.heartbeatsAndCheckView();
    Thread.sleep(3000);
    logger.info("testLocalClusterSyncTokenIdChange: now we should have gotten a CHANGING/CHANGED pair additionally...");
    assertEquals(0, discoveryService.getViewStateManager().waitForAsyncEvents(2000));
    assertEquals(3, listener.countEvents());
}
Also used : FullJR2VirtualInstanceBuilder(org.apache.sling.discovery.impl.setup.FullJR2VirtualInstanceBuilder) ResourceResolverFactory(org.apache.sling.api.resource.ResourceResolverFactory) HeartbeatHandler(org.apache.sling.discovery.impl.common.heartbeat.HeartbeatHandler) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) VirtualInstance(org.apache.sling.discovery.base.its.setup.VirtualInstance) DummyListener(org.apache.sling.discovery.commons.providers.base.DummyListener) Test(org.junit.Test) AbstractDiscoveryServiceTest(org.apache.sling.discovery.base.its.AbstractDiscoveryServiceTest)

Example 24 with ResourceResolverFactory

use of org.apache.sling.api.resource.ResourceResolverFactory 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 25 with ResourceResolverFactory

use of org.apache.sling.api.resource.ResourceResolverFactory in project sling by apache.

the class RepositoryTestHelper method mockResourceResolverFactory.

public static ResourceResolverFactory mockResourceResolverFactory(final SlingRepository repositoryOrNull) throws Exception {
    Mockery context = new JUnit4Mockery() {

        {
            // @see http://www.jmock.org/threading-synchroniser.html
            setThreadingPolicy(new Synchroniser());
        }
    };
    final ResourceResolverFactory resourceResolverFactory = context.mock(ResourceResolverFactory.class);
    // final ResourceResolver resourceResolver = new MockResourceResolver();
    // final ResourceResolver resourceResolver = new
    // MockedResourceResolver();
    context.checking(new Expectations() {

        {
            allowing(resourceResolverFactory).getServiceResourceResolver(null);
            will(new Action() {

                @Override
                public Object invoke(Invocation invocation) throws Throwable {
                    return new MockedResourceResolver(repositoryOrNull);
                }

                @Override
                public void describeTo(Description arg0) {
                    arg0.appendText("whateva - im going to create a new mockedresourceresolver");
                }
            });
        }
    });
    return resourceResolverFactory;
}
Also used : Expectations(org.jmock.Expectations) JUnit4Mockery(org.jmock.integration.junit4.JUnit4Mockery) Action(org.jmock.api.Action) ResourceResolverFactory(org.apache.sling.api.resource.ResourceResolverFactory) Description(org.hamcrest.Description) Invocation(org.jmock.api.Invocation) Synchroniser(org.jmock.lib.concurrent.Synchroniser) Mockery(org.jmock.Mockery) JUnit4Mockery(org.jmock.integration.junit4.JUnit4Mockery)

Aggregations

ResourceResolverFactory (org.apache.sling.api.resource.ResourceResolverFactory)41 Test (org.junit.Test)26 SlingRepository (org.apache.sling.jcr.api.SlingRepository)22 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)16 DistributionRequest (org.apache.sling.distribution.DistributionRequest)13 DefaultDistributionLog (org.apache.sling.distribution.log.impl.DefaultDistributionLog)12 DistributionPackageImporter (org.apache.sling.distribution.packaging.DistributionPackageImporter)12 Before (org.junit.Before)10 Event (javax.jcr.observation.Event)8 Scheduler (org.apache.sling.commons.scheduler.Scheduler)8 DistributionEventFactory (org.apache.sling.distribution.event.impl.DistributionEventFactory)8 DistributionPackageExporter (org.apache.sling.distribution.packaging.DistributionPackageExporter)8 DistributionQueueProvider (org.apache.sling.distribution.queue.DistributionQueueProvider)8 DistributionQueueDispatchingStrategy (org.apache.sling.distribution.queue.impl.DistributionQueueDispatchingStrategy)8 DistributionPackage (org.apache.sling.distribution.packaging.DistributionPackage)7 SimpleDistributionQueue (org.apache.sling.distribution.queue.impl.simple.SimpleDistributionQueue)7 InvocationOnMock (org.mockito.invocation.InvocationOnMock)7 DistributionPackageInfo (org.apache.sling.distribution.packaging.DistributionPackageInfo)6 DistributionQueueItemStatus (org.apache.sling.distribution.queue.DistributionQueueItemStatus)6 Resource (org.apache.sling.api.resource.Resource)5