Package org.osgi.framework

Examples of org.osgi.framework.ServiceRegistration


     */
    @Test(timeout = DEFAULT_TEST_TIMEOUT)
    public void testNoJobProcessor() throws Exception {
        final AtomicInteger count = new AtomicInteger(0);

        final ServiceRegistration eh1 = this.registerJobConsumer(TOPIC,
                new JobConsumer() {

            @Override
            public JobResult process(final Job job) {
                count.incrementAndGet();

                return JobResult.OK;
            }
         });

        try {
            final JobManager jobManager = this.getJobManager();

            // we start 20 jobs, every second job has no processor
            final int COUNT = 20;
            for(int i = 0; i < COUNT; i++ ) {
                final String jobTopic = (i % 2 == 0 ? TOPIC : TOPIC + "2");

                jobManager.addJob(jobTopic, null);
            }
            while ( count.get() < COUNT / 2) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ie) {
                    // ignore
                }
            }

            assertEquals("Finished count", COUNT / 2, count.get());
            // unprocessed count should be 0 as there is no job consumer for this job
            assertEquals("Unprocessed count", 0, jobManager.getStatistics().getNumberOfJobs());
            assertEquals("Finished count", COUNT / 2, jobManager.getStatistics().getNumberOfFinishedJobs());

            // now remove jobs
            for(final Job j : jobManager.findJobs(JobManager.QueryType.ALL, TOPIC + "2", -1, (Map<String, Object>[])null)) {
                jobManager.removeJobById(j.getId());
            }
        } finally {
            eh1.unregister();
        }
    }
View Full Code Here


    @Test(timeout = DEFAULT_TEST_TIMEOUT)
    public void testTimedJob() throws Exception {
        final AtomicInteger counter = new AtomicInteger();

        final ServiceRegistration ehReg = this.registerEventHandler(TOPIC, new EventHandler() {

            @Override
            public void handleEvent(final Event event) {
                if ( TOPIC.equals(event.getTopic()) ) {
                    counter.incrementAndGet();
                }
            }
        });
        try {
            final Date d = new Date();
            d.setTime(System.currentTimeMillis() + 2000); // run in 2 seconds
            // send timed event
            final Dictionary<String, Object> props = new Hashtable<String, Object>();
            props.put(EventUtil.PROPERTY_TIMED_EVENT_TOPIC, TOPIC);
            props.put(EventUtil.PROPERTY_TIMED_EVENT_DATE, d);
            this.eventAdmin.sendEvent(new Event(EventUtil.TOPIC_TIMED_EVENT, props));

            while ( counter.get() == 0 ) {
                this.sleep(1000);
            }
        } finally {
            ehReg.unregister();
        }
    }
View Full Code Here

    @Test(timeout = DEFAULT_TEST_TIMEOUT)
    public void testPeriodicTimedJob() throws Exception {
        final AtomicInteger counter = new AtomicInteger();

        final ServiceRegistration ehReg = this.registerEventHandler(TOPIC, new EventHandler() {

            @Override
            public void handleEvent(final Event event) {
                if ( TOPIC.equals(event.getTopic()) ) {
                    counter.incrementAndGet();
                }
            }
        });
        try {
            // send timed event
            final Dictionary<String, Object> props = new Hashtable<String, Object>();
            props.put(EventUtil.PROPERTY_TIMED_EVENT_TOPIC, TOPIC);
            props.put(EventUtil.PROPERTY_TIMED_EVENT_PERIOD, 1L);
            props.put(EventUtil.PROPERTY_TIMED_EVENT_ID, "id");
            this.eventAdmin.sendEvent(new Event(EventUtil.TOPIC_TIMED_EVENT, props));

            while ( counter.get() < 5 ) {
                this.sleep(1000);
            }
            final Dictionary<String, Object> props2 = new Hashtable<String, Object>();
            props2.put(EventUtil.PROPERTY_TIMED_EVENT_TOPIC, TOPIC);
            props2.put(EventUtil.PROPERTY_TIMED_EVENT_ID, "id");

            this.eventAdmin.sendEvent(new Event(EventUtil.TOPIC_TIMED_EVENT, props2));
            int current = counter.get();
            this.sleep(2000);
            if ( counter.get() != current && counter.get() != current + 1 ) {
                fail("Events are still sent");
            }
        } finally {
            ehReg.unregister();
        }
    }
View Full Code Here

    @Test(timeout = DEFAULT_TEST_TIMEOUT)
    public void testSimpleClassloading() throws Exception {
        final AtomicInteger processedJobsCount = new AtomicInteger(0);
        final List<Event> finishedEvents = Collections.synchronizedList(new ArrayList<Event>());
        final ServiceRegistration jcReg = this.registerJobConsumer(TOPIC,
                new JobConsumer() {
                    @Override
                    public JobResult process(Job job) {
                        processedJobsCount.incrementAndGet();
                        return JobResult.OK;
                    }
                });
        final ServiceRegistration ehReg = this.registerEventHandler(NotificationConstants.TOPIC_JOB_FINISHED,
                new EventHandler() {

                    @Override
                    public void handleEvent(Event event) {
                        finishedEvents.add(event);
                    }
                });
        try {
            final JobManager jobManager = this.getJobManager();

            final List<String> list = new ArrayList<String>();
            list.add("1");
            list.add("2");

            final EventPropertiesMap map = new EventPropertiesMap();
            map.put("a", "a1");
            map.put("b", "b2");

            // we start a single job
            final Map<String, Object> props = new HashMap<String, Object>();
            props.put("string", "Hello");
            props.put("int", new Integer(5));
            props.put("long", new Long(7));
            props.put("list", list);
            props.put("map", map);

            final String jobId = jobManager.addJob(TOPIC, props).getId();

            new RetryLoop(Conditions.collectionIsNotEmptyCondition(finishedEvents,
                    "Waiting for finishedEvents to have at least one element"), 5, 50);

            // no jobs queued, none processed and no available
            new RetryLoop(new RetryLoop.Condition() {

                @Override
                public String getDescription() {
                    return "Waiting for job to be processed. Conditions: queuedJobs=" + jobManager.getStatistics().getNumberOfQueuedJobs() +
                            ", jobsCount=" + processedJobsCount + ", findJobs=" +
                            jobManager.findJobs(JobManager.QueryType.ALL, TOPIC, -1, (Map<String, Object>[]) null)
                            .size();
                }

                @Override
                public boolean isTrue() throws Exception {
                    return jobManager.getStatistics().getNumberOfQueuedJobs() == 0
                            && processedJobsCount.get() == 1
                            && jobManager.findJobs(JobManager.QueryType.ALL, TOPIC, -1, (Map<String, Object>[]) null)
                                    .size() == 0;
                }
            }, CONDITION_TIMEOUT_SECONDS, CONDITION_INTERVAL_MILLIS);

            final String jobTopic = (String)finishedEvents.get(0).getProperty(NotificationConstants.NOTIFICATION_PROPERTY_JOB_TOPIC);
            assertNotNull(jobTopic);
            assertEquals("Hello", finishedEvents.get(0).getProperty("string"));
            assertEquals(new Integer(5), Integer.valueOf(finishedEvents.get(0).getProperty("int").toString()));
            assertEquals(new Long(7), Long.valueOf(finishedEvents.get(0).getProperty("long").toString()));
            assertEquals(list, finishedEvents.get(0).getProperty("list"));
            assertEquals(map, finishedEvents.get(0).getProperty("map"));

            jobManager.removeJobById(jobId);
        } finally {
            jcReg.unregister();
            ehReg.unregister();
        }
    }
View Full Code Here

    @Test(timeout = DEFAULT_TEST_TIMEOUT)
    public void testFailedClassloading() throws Exception {
        final AtomicInteger failedJobsCount = new AtomicInteger(0);
        final List<Event> finishedEvents = Collections.synchronizedList(new ArrayList<Event>());
        final ServiceRegistration jcReg = this.registerJobConsumer(TOPIC + "/failed",
                new JobConsumer() {

                    @Override
                    public JobResult process(Job job) {
                        failedJobsCount.incrementAndGet();
                        return JobResult.OK;
                    }
                });
        final ServiceRegistration ehReg = this.registerEventHandler(NotificationConstants.TOPIC_JOB_FINISHED,
                new EventHandler() {

                    @Override
                    public void handleEvent(Event event) {
                        finishedEvents.add(event);
                    }
                });
        try {
            final JobManager jobManager = this.getJobManager();

            // dao is an invisible class for the dynamic class loader as it is not public
            // therefore scheduling this job should fail!
            final DataObject dao = new DataObject();

            // we start a single job
            final Map<String, Object> props = new HashMap<String, Object>();
            props.put("dao", dao);

            final String id = jobManager.addJob(TOPIC + "/failed", props).getId();

            // wait until the conditions are met
            new RetryLoop(new RetryLoop.Condition() {

                @Override
                public boolean isTrue() throws Exception {
                    return failedJobsCount.get() == 0
                            && finishedEvents.size() == 0
                            && jobManager.findJobs(JobManager.QueryType.ALL, TOPIC + "/failed", -1,
                                    (Map<String, Object>[]) null).size() == 1
                            && jobManager.getStatistics().getNumberOfQueuedJobs() == 1
                            && jobManager.getStatistics().getNumberOfActiveJobs() == 0;
                }

                @Override
                public String getDescription() {
                    return "Waiting for job failure to be recorded. Conditions " +
                           "faildJobsCount=" + failedJobsCount.get() +
                           ", finishedEvents=" + finishedEvents.size() +
                           ", findJobs= " + jobManager.findJobs(JobManager.QueryType.ALL, TOPIC + "/failed", -1,
                                   (Map<String, Object>[]) null).size()
                           +", queuedJobs=" + jobManager.getStatistics().getNumberOfQueuedJobs()
                           +", activeJobs=" + jobManager.getStatistics().getNumberOfActiveJobs();
                }
            }, CONDITION_TIMEOUT_SECONDS, CONDITION_INTERVAL_MILLIS);

            jobManager.removeJobById(id); // moves the job to the history section
            assertEquals(0, jobManager.findJobs(JobManager.QueryType.ALL, TOPIC + "/failed", -1, (Map<String, Object>[])null).size());

            jobManager.removeJobById(id); // removes the job permanently
        } finally {
            jcReg.unregister();
            ehReg.unregister();
        }
    }
View Full Code Here

     * Test history.
     * Start 10 jobs and cancel some of them and succeed others
     */
    @Test(timeout = DEFAULT_TEST_TIMEOUT)
    public void testHistory() throws Exception {
        final ServiceRegistration reg = this.registerJobExecutor(TOPIC,
                new JobExecutor() {

                    @Override
                    public JobExecutionResult process(final Job job, final JobExecutionContext context) {
                        sleep(5L);
                        final long count = job.getProperty(PROP_COUNTER, Long.class);
                        if ( count == 2 || count == 5 || count == 7 ) {
                            return context.result().message(Job.JobState.ERROR.name()).cancelled();
                        }
                        return context.result().message(Job.JobState.SUCCEEDED.name()).succeeded();
                    }

                });
        Collection<Job> col = null;
        try {
            for(int i = 0; i< 10; i++) {
                this.addJob(i);
            }
            this.sleep(200L);
            while ( this.getJobManager().findJobs(JobManager.QueryType.HISTORY, TOPIC, -1, (Map<String, Object>[])null).size() < 10 ) {
                this.sleep(20L);
            }
            col = this.getJobManager().findJobs(JobManager.QueryType.HISTORY, TOPIC, -1, (Map<String, Object>[])null);
            assertEquals(10, col.size());
            assertEquals(0, this.getJobManager().findJobs(JobManager.QueryType.ACTIVE, TOPIC, -1, (Map<String, Object>[])null).size());
            assertEquals(0, this.getJobManager().findJobs(JobManager.QueryType.QUEUED, TOPIC, -1, (Map<String, Object>[])null).size());
            assertEquals(0, this.getJobManager().findJobs(JobManager.QueryType.ALL, TOPIC, -1, (Map<String, Object>[])null).size());
            assertEquals(3, this.getJobManager().findJobs(JobManager.QueryType.CANCELLED, TOPIC, -1, (Map<String, Object>[])null).size());
            assertEquals(0, this.getJobManager().findJobs(JobManager.QueryType.DROPPED, TOPIC, -1, (Map<String, Object>[])null).size());
            assertEquals(3, this.getJobManager().findJobs(JobManager.QueryType.ERROR, TOPIC, -1, (Map<String, Object>[])null).size());
            assertEquals(0, this.getJobManager().findJobs(JobManager.QueryType.GIVEN_UP, TOPIC, -1, (Map<String, Object>[])null).size());
            assertEquals(0, this.getJobManager().findJobs(JobManager.QueryType.STOPPED, TOPIC, -1, (Map<String, Object>[])null).size());
            assertEquals(7, this.getJobManager().findJobs(JobManager.QueryType.SUCCEEDED, TOPIC, -1, (Map<String, Object>[])null).size());
            // verify order, message and state
            long last = 9;
            for(final Job j : col) {
                assertNotNull(j.getFinishedDate());
                final long count = j.getProperty(PROP_COUNTER, Long.class);
                assertEquals(last, count);
                if ( count == 2 || count == 5 || count == 7 ) {
                    assertEquals(Job.JobState.ERROR, j.getJobState());
                } else {
                    assertEquals(Job.JobState.SUCCEEDED, j.getJobState());
                }
                assertEquals(j.getJobState().name(), j.getResultMessage());
                last--;
            }
        } finally {
            if ( col != null ) {
                for(final Job j : col) {
                    this.getJobManager().removeJobById(j.getId());
                }
            }
            reg.unregister();
        }
    }
View Full Code Here

        // register consumer and event handler
        final Barrier cb = new Barrier(2);
        final AtomicInteger count = new AtomicInteger(0);
        final AtomicInteger parallelCount = new AtomicInteger(0);
        final ServiceRegistration jcReg = 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;
                    }
                });
        final ServiceRegistration ehReg = this.registerEventHandler(NotificationConstants.TOPIC_JOB_FINISHED,
                new EventHandler() {

                    @Override
                    public void handleEvent(final Event event) {
                        count.incrementAndGet();
                    }
                });

        try {
            // 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());
        } finally {
            jcReg.unregister();
            ehReg.unregister();
        }
    }
View Full Code Here

    public void testRoundRobinQueue() throws Exception {
        final JobManager jobManager = this.getJobManager();

        final Barrier cb = new Barrier(2);

        final ServiceRegistration jc1Reg = 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 ServiceRegistration jcReg = this.registerJobConsumer(TOPIC + "/*",
                new JobConsumer() {

                    @Override
                    public JobResult process(final Job job) {
                        if ( parallelCount.incrementAndGet() > MAX_PAR ) {
                            parallelCount.decrementAndGet();
                            return JobResult.FAILED;
                        }
                        sleep(30);
                        parallelCount.decrementAndGet();
                        return JobResult.OK;
                    }
                });
        final ServiceRegistration ehReg = this.registerEventHandler(NotificationConstants.TOPIC_JOB_FINISHED,
                new EventHandler() {

                    @Override
                    public void handleEvent(final Event event) {
                        count.incrementAndGet();
                    }
                });

        try {
            // 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:
            // first jobs without id
            for(int i = 0; i < NUM_JOBS; i++ ) {
                final String subTopic = TOPIC + "/sub" + (i % 10);
                jobManager.addJob(subTopic, null);
            }
            // second jobs with id
            for(int i = 0; i < NUM_JOBS; i++ ) {
                final String subTopic = TOPIC + "/sub" + (i % 10);
                jobManager.addJob(subTopic, "id" + i, null);
            }
            // start the queue
            q.resume();
            while ( count.get() < 2 * NUM_JOBS  + 1 ) {
                assertEquals("Failed count", 0, q.getStatistics().getNumberOfFailedJobs());
                assertEquals("Cancelled count", 0, q.getStatistics().getNumberOfCancelledJobs());
                sleep(500);
            }
            // we started one event before the test, so add one
            assertEquals("Finished count", 2 * NUM_JOBS + 1, count.get());
            assertEquals("Finished count", 2 * NUM_JOBS + 1, jobManager.getStatistics().getNumberOfFinishedJobs());
            assertEquals("Finished count", 2 * NUM_JOBS + 1, q.getStatistics().getNumberOfFinishedJobs());
            assertEquals("Failed count", 0, q.getStatistics().getNumberOfFailedJobs());
            assertEquals("Cancelled count", 0, q.getStatistics().getNumberOfCancelledJobs());
        } finally {
            jc1Reg.unregister();
            jcReg.unregister();
            ehReg.unregister();
        }
    }
View Full Code Here

                "String[]", oldQueue, getQueueNames()));
    }

    private QueueMBeanHolder add(Queue queue) {
        QueueMBeanImpl queueMBean = new QueueMBeanImpl(queue);
        ServiceRegistration serviceRegistration = bundleContext
                .registerService(StatisticsMBean.class.getName(), queueMBean,
                        createProperties(
                                "jmx.objectname","org.apache.sling:type=queues,name="+queue.getName(),
                                Constants.SERVICE_DESCRIPTION, "QueueMBean for queue "+queue.getName(),
                                Constants.SERVICE_VENDOR, "The Apache Software Foundation"));
View Full Code Here

            {
                createdLatch.countDown();
            }
        };

        ServiceRegistration reg = m_context.registerService(HttpSessionListener.class.getName(), listener, null);

        register("/session", new TestServlet()
        {
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
            {
                HttpSession session = req.getSession();
                session.setMaxInactiveInterval(2);

                resp.setStatus(SC_OK);
                resp.flushBuffer();
            }
        });

        try
        {
            assertContent(SC_OK, null, new URL("http://localhost:8080/session"));

            // Session should been created...
            assertTrue(createdLatch.await(50, TimeUnit.SECONDS));

            assertContent(SC_OK, null, new URL("http://localhost:8080/session"));

            // Session should timeout automatically...
            assertTrue(destroyedLatch.await(50, TimeUnit.SECONDS));
        }
        finally
        {
            reg.unregister();
        }
    }
View Full Code Here

TOP

Related Classes of org.osgi.framework.ServiceRegistration

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.