Search in sources :

Example 1 with ResourceResolverFactory

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

the class HeartbeatTest method testVotingLoop.

/**
     * SLING-5027 : test to reproduce the voting loop
     * (and verify that it's fixed)
     */
@Test
public void testVotingLoop() throws Throwable {
    logger.info("testVotingLoop: creating slowMachine1...");
    FullJR2VirtualInstanceBuilder slowBuilder1 = newBuilder();
    slowBuilder1.setDebugName("slow1").newRepository("/var/discovery/impl/", true).setConnectorPingTimeout(600).setConnectorPingInterval(999).setMinEventDelay(0);
    FullJR2VirtualInstance slowMachine1 = slowBuilder1.fullBuild();
    instances.add(slowMachine1);
    SimpleTopologyEventListener slowListener1 = new SimpleTopologyEventListener("slow1");
    slowMachine1.bindTopologyEventListener(slowListener1);
    logger.info("testVotingLoop: creating slowMachine2...");
    FullJR2VirtualInstanceBuilder slowBuilder2 = newBuilder();
    slowBuilder2.setDebugName("slow2").useRepositoryOf(slowMachine1).setConnectorPingTimeout(600).setConnectorPingInterval(999).setMinEventDelay(0);
    FullJR2VirtualInstance slowMachine2 = slowBuilder2.fullBuild();
    instances.add(slowMachine2);
    SimpleTopologyEventListener slowListener2 = new SimpleTopologyEventListener("slow2");
    slowMachine2.bindTopologyEventListener(slowListener2);
    logger.info("testVotingLoop: creating fastMachine...");
    FullJR2VirtualInstanceBuilder fastBuilder = newBuilder();
    fastBuilder.setDebugName("fast").useRepositoryOf(slowMachine1).setConnectorPingTimeout(600).setConnectorPingInterval(999).setMinEventDelay(0);
    FullJR2VirtualInstance fastMachine = fastBuilder.fullBuild();
    instances.add(fastMachine);
    SimpleTopologyEventListener fastListener = new SimpleTopologyEventListener("fast");
    fastMachine.bindTopologyEventListener(fastListener);
    HeartbeatHandler hhSlow1 = slowMachine1.getHeartbeatHandler();
    HeartbeatHandler hhSlow2 = slowMachine2.getHeartbeatHandler();
    HeartbeatHandler hhFast = fastMachine.getHeartbeatHandler();
    Thread.sleep(1000);
    logger.info("testVotingLoop: after some initial 1sec sleep no event should yet have been sent");
    assertFalse(fastMachine.getDiscoveryService().getTopology().isCurrent());
    assertFalse(slowMachine1.getDiscoveryService().getTopology().isCurrent());
    assertFalse(slowMachine2.getDiscoveryService().getTopology().isCurrent());
    assertNull(fastListener.getLastEvent());
    assertNull(slowListener1.getLastEvent());
    assertNull(slowListener2.getLastEvent());
    // prevent the slow machine from voting
    logger.info("testVotingLoop: stopping voting of slowMachine1...");
    slowMachine1.stopVoting();
    // now let all issue a heartbeat
    logger.info("testVotingLoop: letting slow1, slow2 and fast all issue 1 heartbeat");
    hhSlow1.issueHeartbeat();
    hhSlow2.issueHeartbeat();
    hhFast.issueHeartbeat();
    // now let the fast one start a new voting, to which
    // only the fast one will vote, the slow one doesn't.
    // that will cause a voting loop
    logger.info("testVotingLoop: let the fast one do a checkView, thus initiate a voting");
    hhFast.doCheckView();
    Calendar previousVotedAt = null;
    for (int i = 0; i < 5; i++) {
        logger.info("testVotingLoop: sleeping 1sec...");
        Thread.sleep(1000);
        logger.info("testVotingLoop: check to see that there is no voting loop...");
        // now check the ongoing votings
        ResourceResolverFactory factory = fastMachine.getResourceResolverFactory();
        ResourceResolver resourceResolver = factory.getServiceResourceResolver(null);
        try {
            List<VotingView> ongoingVotings = VotingHelper.listOpenNonWinningVotings(resourceResolver, fastMachine.getFullConfig());
            assertNotNull(ongoingVotings);
            assertEquals(1, ongoingVotings.size());
            VotingView ongoingVote = ongoingVotings.get(0);
            assertFalse(ongoingVote.isWinning());
            assertFalse(ongoingVote.hasVotedYes(slowMachine1.getSlingId()));
            assertTrue(ongoingVote.hasVotedYes(slowMachine2.getSlingId()));
            final Resource memberResource = ongoingVote.getResource().getChild("members").getChild(slowMachine2.getSlingId());
            final ModifiableValueMap memberMap = memberResource.adaptTo(ModifiableValueMap.class);
            Property vote = (Property) memberMap.get("vote");
            assertEquals(Boolean.TRUE, vote.getBoolean());
            Property votedAt = (Property) memberMap.get("votedAt");
            if (previousVotedAt == null) {
                previousVotedAt = votedAt.getDate();
            } else {
                assertEquals(previousVotedAt, votedAt.getDate());
            }
        } catch (Exception e) {
            resourceResolver.close();
            fail("Exception: " + e);
        }
    }
}
Also used : FullJR2VirtualInstance(org.apache.sling.discovery.impl.setup.FullJR2VirtualInstance) Calendar(java.util.Calendar) Resource(org.apache.sling.api.resource.Resource) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) FullJR2VirtualInstanceBuilder(org.apache.sling.discovery.impl.setup.FullJR2VirtualInstanceBuilder) ResourceResolverFactory(org.apache.sling.api.resource.ResourceResolverFactory) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) VotingView(org.apache.sling.discovery.impl.cluster.voting.VotingView) Property(javax.jcr.Property) Test(org.junit.Test)

Example 2 with ResourceResolverFactory

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

the class JobManagerConfiguration method createResourceResolver.

/**
     * Create a new resource resolver for reading and writing the resource tree.
     * The resolver needs to be closed by the client.
     * @return A resource resolver or {@code null} if the component is already deactivated.
     * @throws RuntimeException if the resolver can't be created.
     */
public ResourceResolver createResourceResolver() {
    ResourceResolver resolver = null;
    final ResourceResolverFactory factory = this.resourceResolverFactory;
    if (factory != null) {
        try {
            resolver = this.resourceResolverFactory.getServiceResourceResolver(null);
        } catch (final LoginException le) {
            logger.error("Unable to create new resource resolver: " + le.getMessage(), le);
            throw new RuntimeException(le);
        }
    }
    return resolver;
}
Also used : ResourceResolverFactory(org.apache.sling.api.resource.ResourceResolverFactory) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) LoginException(org.apache.sling.api.resource.LoginException)

Example 3 with ResourceResolverFactory

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

the class AbstractJobHandlingTest method cleanup.

public void cleanup() {
    // clean job area
    final ServiceReference<ResourceResolverFactory> ref = this.bc.getServiceReference(ResourceResolverFactory.class);
    final ResourceResolverFactory factory = this.bc.getService(ref);
    ResourceResolver resolver = null;
    try {
        resolver = factory.getAdministrativeResourceResolver(null);
        final Resource rsrc = resolver.getResource("/var/eventing");
        if (rsrc != null) {
            delete(rsrc);
            resolver.commit();
        }
    } catch (final LoginException le) {
    // ignore
    } catch (final PersistenceException e) {
    // ignore
    } catch (final Exception e) {
    // sometimes an NPE is thrown from the repository, as we
    // are in the cleanup, we can ignore this
    } finally {
        if (resolver != null) {
            resolver.close();
        }
    }
    // unregister all services
    for (final ServiceRegistration<?> reg : this.registrations) {
        reg.unregister();
    }
    this.registrations.clear();
    // remove all configurations
    try {
        final org.osgi.service.cm.Configuration[] cfgs = this.configAdmin.listConfigurations(null);
        if (cfgs != null) {
            for (final org.osgi.service.cm.Configuration c : cfgs) {
                try {
                    c.delete();
                } catch (final IOException io) {
                // ignore
                }
            }
        }
    } catch (final IOException io) {
    // ignore
    } catch (final InvalidSyntaxException e) {
    // ignore
    }
    this.sleep(1000);
}
Also used : Configuration(org.ops4j.pax.exam.Configuration) JobManagerConfiguration(org.apache.sling.event.impl.jobs.config.JobManagerConfiguration) Resource(org.apache.sling.api.resource.Resource) IOException(java.io.IOException) PersistenceException(org.apache.sling.api.resource.PersistenceException) BundleException(org.osgi.framework.BundleException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) IOException(java.io.IOException) LoginException(org.apache.sling.api.resource.LoginException) 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) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException)

Example 4 with ResourceResolverFactory

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

the class SlingServletResolverTest method setUp.

@Before
public void setUp() throws Exception {
    mockResourceResolver = new MockResourceResolver() {

        @Override
        public void close() {
        // nothing to do;
        }

        @Override
        public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
            return null;
        }

        @Override
        public ResourceResolver clone(Map<String, Object> authenticationInfo) throws LoginException {
            throw new LoginException("MockResourceResolver can't be cloned - excepted for this test!");
        }

        @Override
        public void refresh() {
        // nothing to do
        }
    };
    mockResourceResolver.setSearchPath("/");
    final ResourceResolverFactory factory = new ResourceResolverFactory() {

        @Override
        public ResourceResolver getAdministrativeResourceResolver(Map<String, Object> authenticationInfo) throws LoginException {
            return mockResourceResolver;
        }

        @Override
        public ResourceResolver getResourceResolver(Map<String, Object> authenticationInfo) throws LoginException {
            return mockResourceResolver;
        }

        @Override
        public ResourceResolver getServiceResourceResolver(Map<String, Object> authenticationInfo) throws LoginException {
            return mockResourceResolver;
        }

        @Override
        public ResourceResolver getThreadResourceResolver() {
            // TODO Auto-generated method stub
            return null;
        }
    };
    servlet = new MockSlingRequestHandlerServlet();
    servletResolver = new SlingServletResolver();
    Class<?> resolverClass = servletResolver.getClass();
    // set resource resolver factory
    final Field resolverField = resolverClass.getDeclaredField("resourceResolverFactory");
    resolverField.setAccessible(true);
    resolverField.set(servletResolver, factory);
    MockBundle bundle = new MockBundle(1L);
    MockBundleContext bundleContext = new MockBundleContext(bundle) {

        @Override
        public ServiceRegistration registerService(String s, Object o, Dictionary dictionary) {
            return null;
        }

        @Override
        public ServiceRegistration registerService(String[] strings, Object o, Dictionary dictionary) {
            return null;
        }
    };
    MockServiceReference serviceReference = new MockServiceReference(bundle);
    serviceReference.setProperty(Constants.SERVICE_ID, 1L);
    serviceReference.setProperty(ServletResolverConstants.SLING_SERVLET_NAME, SERVLET_NAME);
    serviceReference.setProperty(ServletResolverConstants.SLING_SERVLET_PATHS, SERVLET_PATH);
    serviceReference.setProperty(ServletResolverConstants.SLING_SERVLET_EXTENSIONS, SERVLET_EXTENSION);
    servletResolver.bindServlet(SlingServletResolverTest.this.servlet, serviceReference);
    servletResolver.activate(bundleContext, new SlingServletResolver.Config() {

        @Override
        public Class<? extends Annotation> annotationType() {
            return SlingServletResolver.Config.class;
        }

        @Override
        public String servletresolver_servletRoot() {
            return "0";
        }

        @Override
        public String[] servletresolver_paths() {
            return new String[] { "/" };
        }

        @Override
        public String[] servletresolver_defaultExtensions() {
            // TODO Auto-generated method stub
            return new String[] { "html" };
        }

        @Override
        public int servletresolver_cacheSize() {
            return 200;
        }
    });
    String path = "/" + MockSlingHttpServletRequest.RESOURCE_TYPE + "/" + ResourceUtil.getName(MockSlingHttpServletRequest.RESOURCE_TYPE) + ".servlet";
    MockServletResource res = new MockServletResource(mockResourceResolver, servlet, path);
    mockResourceResolver.addResource(res);
    MockResource parent = new MockResource(mockResourceResolver, ResourceUtil.getParent(res.getPath()), "nt:folder");
    mockResourceResolver.addResource(parent);
    List<Resource> childRes = new ArrayList<>();
    childRes.add(res);
    mockResourceResolver.addChildren(parent, childRes);
}
Also used : Dictionary(java.util.Dictionary) MockResource(org.apache.sling.commons.testing.sling.MockResource) ArrayList(java.util.ArrayList) Field(java.lang.reflect.Field) ResourceResolverFactory(org.apache.sling.api.resource.ResourceResolverFactory) MockResourceResolver(org.apache.sling.commons.testing.sling.MockResourceResolver) MockBundle(org.apache.sling.commons.testing.osgi.MockBundle) MockServletResource(org.apache.sling.servlets.resolver.internal.resource.MockServletResource) Resource(org.apache.sling.api.resource.Resource) MockResource(org.apache.sling.commons.testing.sling.MockResource) MockServletResource(org.apache.sling.servlets.resolver.internal.resource.MockServletResource) Annotation(java.lang.annotation.Annotation) MockServiceReference(org.apache.sling.commons.testing.osgi.MockServiceReference) MockBundleContext(org.apache.sling.commons.testing.osgi.MockBundleContext) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) MockResourceResolver(org.apache.sling.commons.testing.sling.MockResourceResolver) LoginException(org.apache.sling.api.resource.LoginException) Map(java.util.Map) Before(org.junit.Before)

Example 5 with ResourceResolverFactory

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

the class JcrEventDistributionTriggerTest method testProcessEventOnMultipleIgnoredPattern.

@Test
public void testProcessEventOnMultipleIgnoredPattern() throws Exception {
    SlingRepository repository = mock(SlingRepository.class);
    Scheduler scheduler = mock(Scheduler.class);
    ResourceResolverFactory resolverFactory = mock(ResourceResolverFactory.class);
    String path = "/home/users";
    String serviceName = "serviceId";
    String[] ignoredPaths = new String[] { ".*/.tokens.*", ".*/.rep:cache.*" };
    JcrEventDistributionTrigger jcrEventdistributionTrigger = new JcrEventDistributionTrigger(repository, scheduler, resolverFactory, path, false, serviceName, ignoredPaths);
    Event event = mock(Event.class);
    when(event.getPath()).thenReturn("/home/users/3/3U3HxUUzJJ60BdN4lEDJ/.tokens/2017-01-10T15.52.37.842+01.00");
    DistributionRequest distributionRequest = jcrEventdistributionTrigger.processEvent(event);
    assertNull(distributionRequest);
}
Also used : SlingRepository(org.apache.sling.jcr.api.SlingRepository) DistributionRequest(org.apache.sling.distribution.DistributionRequest) ResourceResolverFactory(org.apache.sling.api.resource.ResourceResolverFactory) Scheduler(org.apache.sling.commons.scheduler.Scheduler) Event(javax.jcr.observation.Event) Test(org.junit.Test)

Aggregations

ResourceResolverFactory (org.apache.sling.api.resource.ResourceResolverFactory)43 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 LoginException (org.apache.sling.api.resource.LoginException)6 DistributionPackageInfo (org.apache.sling.distribution.packaging.DistributionPackageInfo)6 DistributionQueueItemStatus (org.apache.sling.distribution.queue.DistributionQueueItemStatus)6