Search in sources :

Example 6 with EventHandler

use of org.osgi.service.event.EventHandler in project sling by apache.

the class ChaosTest method testDoChaos.

@Test(timeout = DURATION * 16000L)
public void testDoChaos() throws Exception {
    final JobManager jobManager = this.getJobManager();
    // setup added, created and finished map
    // added and finished are filled by notifications
    // created is filled by the threads starting jobs
    final Map<String, AtomicLong> added = new HashMap<>();
    final Map<String, AtomicLong> created = new HashMap<>();
    final Map<String, AtomicLong> finished = new HashMap<>();
    final List<String> topics = new ArrayList<>();
    for (int i = 0; i < NUM_ORDERED_TOPICS; i++) {
        added.put(ORDERED_TOPICS[i], new AtomicLong());
        created.put(ORDERED_TOPICS[i], new AtomicLong());
        finished.put(ORDERED_TOPICS[i], new AtomicLong());
        topics.add(ORDERED_TOPICS[i]);
    }
    for (int i = 0; i < NUM_PARALLEL_TOPICS; i++) {
        added.put(PARALLEL_TOPICS[i], new AtomicLong());
        created.put(PARALLEL_TOPICS[i], new AtomicLong());
        finished.put(PARALLEL_TOPICS[i], new AtomicLong());
        topics.add(PARALLEL_TOPICS[i]);
    }
    for (int i = 0; i < NUM_ROUND_TOPICS; i++) {
        added.put(ROUND_TOPICS[i], new AtomicLong());
        created.put(ROUND_TOPICS[i], new AtomicLong());
        finished.put(ROUND_TOPICS[i], new AtomicLong());
        topics.add(ROUND_TOPICS[i]);
    }
    final List<Thread> threads = new ArrayList<>();
    final AtomicLong finishedThreads = new AtomicLong();
    this.registerEventHandler("org/apache/sling/event/notification/job/*", new EventHandler() {

        @Override
        public void handleEvent(final Event event) {
            final String topic = (String) event.getProperty(NotificationConstants.NOTIFICATION_PROPERTY_JOB_TOPIC);
            if (NotificationConstants.TOPIC_JOB_FINISHED.equals(event.getTopic())) {
                finished.get(topic).incrementAndGet();
            } else if (NotificationConstants.TOPIC_JOB_ADDED.equals(event.getTopic())) {
                added.get(topic).incrementAndGet();
            }
        }
    });
    // setup job consumers
    this.setupJobConsumers();
    // setup job creation tests
    this.setupJobCreationThreads(threads, jobManager, created, finishedThreads);
    this.setupChaosThreads(threads, finishedThreads);
    System.out.println("Starting threads...");
    // start threads
    for (final Thread t : threads) {
        t.setDaemon(true);
        t.start();
    }
    System.out.println("Sleeping for " + DURATION + " seconds to wait for threads to finish...");
    // for sure we can sleep for the duration
    this.sleep(DURATION * 1000);
    System.out.println("Polling for threads to finish...");
    // wait until threads are finished
    while (finishedThreads.get() < threads.size()) {
        this.sleep(100);
    }
    System.out.println("Waiting for job handling to finish...");
    final Set<String> allTopics = new HashSet<>(topics);
    while (!allTopics.isEmpty()) {
        final Iterator<String> iter = allTopics.iterator();
        while (iter.hasNext()) {
            final String topic = iter.next();
            if (finished.get(topic).get() == created.get(topic).get()) {
                iter.remove();
            }
        }
        this.sleep(100);
    }
/* We could try to enable this with Oak again - but right now JR observation handler is too
 * slow.
            System.out.println("Checking notifications...");
            for(final String topic : topics) {
                assertEquals("Checking topic " + topic, created.get(topic).get(), added.get(topic).get());
            }
 */
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) EventHandler(org.osgi.service.event.EventHandler) JobManager(org.apache.sling.event.jobs.JobManager) AtomicLong(java.util.concurrent.atomic.AtomicLong) TopologyEvent(org.apache.sling.discovery.TopologyEvent) Event(org.osgi.service.event.Event) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 7 with EventHandler

use of org.osgi.service.event.EventHandler in project sling by apache.

the class OrderedQueueTest method testOrderedQueue.

/**
     * Ordered Queue Test
     */
@Test(timeout = DEFAULT_TEST_TIMEOUT)
public void testOrderedQueue() throws Exception {
    final JobManager jobManager = this.getJobManager();
    // register consumer and event handler
    final Barrier cb = new Barrier(2);
    final AtomicInteger count = new AtomicInteger(0);
    final AtomicInteger parallelCount = new AtomicInteger(0);
    this.registerJobConsumer("sling/orderedtest/*", new JobConsumer() {

        private volatile int lastCounter = -1;

        @Override
        public JobResult process(final Job job) {
            final int counter = job.getProperty("counter", -10);
            assertNotEquals("Counter property is missing", -10, counter);
            assertTrue("Counter should only increment by max of 1 " + counter + " - " + lastCounter, counter == lastCounter || counter == lastCounter + 1);
            lastCounter = counter;
            if ("sling/orderedtest/start".equals(job.getTopic())) {
                cb.block();
                return JobResult.OK;
            }
            if (parallelCount.incrementAndGet() > 1) {
                parallelCount.decrementAndGet();
                return JobResult.FAILED;
            }
            final String topic = job.getTopic();
            if (topic.endsWith("sub1")) {
                final int i = (Integer) job.getProperty(Job.PROPERTY_JOB_RETRY_COUNT);
                if (i == 0) {
                    parallelCount.decrementAndGet();
                    return JobResult.FAILED;
                }
            }
            try {
                Thread.sleep(30);
            } catch (InterruptedException ie) {
            // ignore
            }
            parallelCount.decrementAndGet();
            return JobResult.OK;
        }
    });
    this.registerEventHandler(NotificationConstants.TOPIC_JOB_FINISHED, new EventHandler() {

        @Override
        public void handleEvent(final Event event) {
            count.incrementAndGet();
        }
    });
    // we first sent one event to get the queue started
    final Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("counter", -1);
    jobManager.addJob("sling/orderedtest/start", properties);
    assertTrue("No event received in the given time.", cb.block(5));
    cb.reset();
    // get the queue
    final Queue q = jobManager.getQueue("orderedtest");
    assertNotNull("Queue 'orderedtest' should exist!", q);
    // suspend it
    q.suspend();
    final int NUM_JOBS = 30;
    // we start "some" jobs:
    for (int i = 0; i < NUM_JOBS; i++) {
        final String subTopic = "sling/orderedtest/sub" + (i % 10);
        properties.clear();
        properties.put("counter", i);
        jobManager.addJob(subTopic, properties);
    }
    // start the queue
    q.resume();
    while (count.get() < NUM_JOBS + 1) {
        try {
            Thread.sleep(500);
        } catch (InterruptedException ie) {
        // ignore
        }
    }
    // we started one event before the test, so add one
    assertEquals("Finished count", NUM_JOBS + 1, count.get());
    assertEquals("Finished count", NUM_JOBS + 1, jobManager.getStatistics().getNumberOfFinishedJobs());
    assertEquals("Finished count", NUM_JOBS + 1, q.getStatistics().getNumberOfFinishedJobs());
    assertEquals("Failed count", NUM_JOBS / 10, q.getStatistics().getNumberOfFailedJobs());
    assertEquals("Cancelled count", 0, q.getStatistics().getNumberOfCancelledJobs());
}
Also used : HashMap(java.util.HashMap) EventHandler(org.osgi.service.event.EventHandler) Barrier(org.apache.sling.event.impl.Barrier) JobManager(org.apache.sling.event.jobs.JobManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Event(org.osgi.service.event.Event) JobConsumer(org.apache.sling.event.jobs.consumer.JobConsumer) Job(org.apache.sling.event.jobs.Job) Queue(org.apache.sling.event.jobs.Queue) Test(org.junit.Test)

Example 8 with EventHandler

use of org.osgi.service.event.EventHandler in project eclipse.themes.darker by jinmingjian.

the class DarkerThemer method onExecute.

@Execute
public void onExecute() {
    eventBroker.subscribe(IThemeEngine.Events.THEME_CHANGED, new EventHandler() {

        public void handleEvent(Event event) {
            ITheme currentTheme = (ITheme) event.getProperty(IThemeEngine.Events.THEME);
            // THEME_DARKER_PREF_THEMEENABLED, false))
            if (currentTheme.getId().equals(THEME_DARKER_ID)) {
                setupPreferences();
                isLastThemeDarker = true;
                DarkerWeavingHook.enableWeaving();
                hookDarkerCore();
            } else if (isLastThemeDarker) {
                DarkerWeavingHook.disableWeaving();
                setToDefaultPreferences();
            }
        }
    });
}
Also used : ITheme(org.eclipse.e4.ui.css.swt.theme.ITheme) EventHandler(org.osgi.service.event.EventHandler) Event(org.osgi.service.event.Event) Execute(org.eclipse.e4.core.di.annotations.Execute)

Example 9 with EventHandler

use of org.osgi.service.event.EventHandler in project sling by apache.

the class JobHandlingTest method testManyJobs.

@Test(timeout = DEFAULT_TEST_TIMEOUT)
public void testManyJobs() throws Exception {
    this.registerJobConsumer(TOPIC, new JobConsumer() {

        @Override
        public JobResult process(final Job job) {
            return JobResult.OK;
        }
    });
    final AtomicInteger count = new AtomicInteger(0);
    this.registerEventHandler(NotificationConstants.TOPIC_JOB_FINISHED, new EventHandler() {

        @Override
        public void handleEvent(final Event event) {
            count.incrementAndGet();
        }
    });
    // we start "some" jobs
    final int COUNT = 300;
    for (int i = 0; i < COUNT; i++) {
        this.getJobManager().addJob(TOPIC, null);
    }
    while (count.get() < COUNT) {
        this.sleep(50);
    }
    assertEquals("Finished count", COUNT, count.get());
    assertEquals("Finished count", COUNT, this.getJobManager().getStatistics().getNumberOfFinishedJobs());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EventHandler(org.osgi.service.event.EventHandler) Event(org.osgi.service.event.Event) JobConsumer(org.apache.sling.event.jobs.consumer.JobConsumer) Job(org.apache.sling.event.jobs.Job) Test(org.junit.Test)

Example 10 with EventHandler

use of org.osgi.service.event.EventHandler in project sling by apache.

the class RoundRobinQueueTest method testRoundRobinQueue.

@Test(timeout = DEFAULT_TEST_TIMEOUT)
public void testRoundRobinQueue() throws Exception {
    final JobManager jobManager = this.getJobManager();
    final Barrier cb = new Barrier(2);
    this.registerJobConsumer(TOPIC + "/start", new JobConsumer() {

        @Override
        public JobResult process(final Job job) {
            cb.block();
            return JobResult.OK;
        }
    });
    // register new consumer and event handle
    final AtomicInteger count = new AtomicInteger(0);
    final AtomicInteger parallelCount = new AtomicInteger(0);
    final Set<Integer> maxParticipants = new HashSet<Integer>();
    this.registerJobConsumer(TOPIC + "/*", new JobConsumer() {

        @Override
        public JobResult process(final Job job) {
            final int max = parallelCount.incrementAndGet();
            if (max > MAX_PAR) {
                parallelCount.decrementAndGet();
                return JobResult.FAILED;
            }
            synchronized (maxParticipants) {
                maxParticipants.add(max);
            }
            sleep(job.getProperty("sleep", 30));
            parallelCount.decrementAndGet();
            return JobResult.OK;
        }
    });
    this.registerEventHandler(NotificationConstants.TOPIC_JOB_FINISHED, new EventHandler() {

        @Override
        public void handleEvent(final Event event) {
            count.incrementAndGet();
        }
    });
    // we first sent one event to get the queue started
    jobManager.addJob(TOPIC + "/start", null);
    assertTrue("No event received in the given time.", cb.block(5));
    cb.reset();
    // get the queue
    final Queue q = jobManager.getQueue(QUEUE_NAME);
    assertNotNull("Queue '" + QUEUE_NAME + "' should exist!", q);
    // suspend it
    q.suspend();
    // we start "some" jobs:
    for (int i = 0; i < NUM_JOBS; i++) {
        final String subTopic = TOPIC + "/sub" + (i % 10);
        final Map<String, Object> props = new HashMap<String, Object>();
        if (i < 10) {
            props.put("sleep", 300);
        } else {
            props.put("sleep", 30);
        }
        jobManager.addJob(subTopic, props);
    }
    // start the queue
    q.resume();
    while (count.get() < NUM_JOBS + 1) {
        assertEquals("Failed count", 0, q.getStatistics().getNumberOfFailedJobs());
        assertEquals("Cancelled count", 0, q.getStatistics().getNumberOfCancelledJobs());
        sleep(300);
    }
    // we started one event before the test, so add one
    assertEquals("Finished count", NUM_JOBS + 1, count.get());
    assertEquals("Finished count", NUM_JOBS + 1, jobManager.getStatistics().getNumberOfFinishedJobs());
    assertEquals("Finished count", NUM_JOBS + 1, q.getStatistics().getNumberOfFinishedJobs());
    assertEquals("Failed count", 0, q.getStatistics().getNumberOfFailedJobs());
    assertEquals("Cancelled count", 0, q.getStatistics().getNumberOfCancelledJobs());
    for (int i = 1; i <= MAX_PAR; i++) {
        assertTrue("# Participants " + String.valueOf(i) + " not in " + maxParticipants, maxParticipants.contains(i));
    }
}
Also used : HashMap(java.util.HashMap) EventHandler(org.osgi.service.event.EventHandler) Barrier(org.apache.sling.event.impl.Barrier) JobManager(org.apache.sling.event.jobs.JobManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Event(org.osgi.service.event.Event) JobConsumer(org.apache.sling.event.jobs.consumer.JobConsumer) Job(org.apache.sling.event.jobs.Job) Queue(org.apache.sling.event.jobs.Queue) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

Event (org.osgi.service.event.Event)13 EventHandler (org.osgi.service.event.EventHandler)13 Test (org.junit.Test)10 Job (org.apache.sling.event.jobs.Job)9 JobManager (org.apache.sling.event.jobs.JobManager)7 JobConsumer (org.apache.sling.event.jobs.consumer.JobConsumer)7 HashMap (java.util.HashMap)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 Barrier (org.apache.sling.event.impl.Barrier)5 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 Queue (org.apache.sling.event.jobs.Queue)3 IOException (java.io.IOException)2 Hashtable (java.util.Hashtable)2 JobExecutionContext (org.apache.sling.event.jobs.consumer.JobExecutionContext)2 JobExecutionResult (org.apache.sling.event.jobs.consumer.JobExecutionResult)2 JobExecutor (org.apache.sling.event.jobs.consumer.JobExecutor)2 IResourceChangeEvent (org.eclipse.core.resources.IResourceChangeEvent)2 Bundle (org.osgi.framework.Bundle)2 PersistenceException (org.talend.commons.exception.PersistenceException)2