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.");
}
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());
}
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());
}
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);
}
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;
}
Aggregations