Search in sources :

Example 1 with JobManagerCallbackAdapter

use of com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter in project android-priority-jobqueue by yigit.

the class JobManagerTestBase method waitUntilAJobIsDone.

@SuppressLint("NewApi")
protected void waitUntilAJobIsDone(final JobManager jobManager, final WaitUntilCallback callback) throws InterruptedException {
    final CountDownLatch runJob = new CountDownLatch(1);
    final Throwable[] throwable = new Throwable[1];
    jobManager.addCallback(new JobManagerCallbackAdapter() {

        @Override
        public void onDone(@NonNull Job job) {
            synchronized (this) {
                super.onDone(job);
                if (callback != null) {
                    try {
                        callback.assertJob(job);
                    } catch (Throwable t) {
                        throwable[0] = t;
                    }
                }
                runJob.countDown();
                jobManager.removeCallback(this);
            }
        }
    });
    if (callback != null) {
        callback.run();
    }
    MatcherAssert.assertThat("The job should be done", runJob.await(1, TimeUnit.MINUTES), is(true));
    MatcherAssert.assertThat("Job assertion failed", throwable[0], CoreMatchers.nullValue());
}
Also used : JobManagerCallbackAdapter(com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter) CountDownLatch(java.util.concurrent.CountDownLatch) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Job(com.birbit.android.jobqueue.Job) SuppressLint(android.annotation.SuppressLint)

Example 2 with JobManagerCallbackAdapter

use of com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter in project android-priority-jobqueue by yigit.

the class JobManagerTestBase method waitUntilJobsAreDone.

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
protected void waitUntilJobsAreDone(final JobManager jobManager, List<? extends Job> jobs, Runnable action) throws InterruptedException {
    final Set<String> uuids = new HashSet<>();
    for (Job job : jobs) {
        uuids.add(job.getId());
    }
    final CountDownLatch latch = new CountDownLatch(uuids.size());
    jobManager.addCallback(new JobManagerCallbackAdapter() {

        @Override
        public void onDone(@NonNull Job job) {
            if (uuids.remove(job.getId())) {
                latch.countDown();
            }
        }
    });
    if (action != null) {
        action.run();
    }
    MatcherAssert.assertThat("Jobs should be done", latch.await(1, TimeUnit.MINUTES), is(true));
}
Also used : JobManagerCallbackAdapter(com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Job(com.birbit.android.jobqueue.Job) CountDownLatch(java.util.concurrent.CountDownLatch) HashSet(java.util.HashSet) TargetApi(android.annotation.TargetApi)

Example 3 with JobManagerCallbackAdapter

use of com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter in project android-priority-jobqueue by yigit.

the class JobStatusTest method testJobStatus.

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Test
public void testJobStatus() throws InterruptedException {
    DummyNetworkUtilWithConnectivityEventSupport networkUtil = new DummyNetworkUtilWithConnectivityEventSupport();
    networkUtil.setNetworkStatus(NetworkUtil.DISCONNECTED, true);
    final JobManager jobManager = createJobManager(new Configuration.Builder(RuntimeEnvironment.application).networkUtil(networkUtil).timer(mockTimer));
    jobManager.stop();
    List<Integer> networkRequiringJobIndices = new ArrayList<Integer>();
    Job[] jobs = new Job[] { new DummyJob(new Params(0)), new DummyJob(new Params(0).persist()), new DummyJob(new Params(0).persist().requireNetwork().addTags(REQ_NETWORK_TAG)) };
    String[] ids = new String[jobs.length];
    networkRequiringJobIndices.add(2);
    for (int i = 0; i < jobs.length; i++) {
        jobManager.addJob(jobs[i]);
        ids[i] = jobs[i].getId();
        JobStatus expectedStatus = (!networkUtil.isDisconnected() || !networkRequiringJobIndices.contains(i)) ? JobStatus.WAITING_READY : JobStatus.WAITING_NOT_READY;
        assertThat("job should have correct status after being added", jobManager.getJobStatus(ids[i]), is(expectedStatus));
    }
    //create an unknown id, ensure status for that
    boolean exists;
    String unknownId;
    do {
        unknownId = UUID.randomUUID().toString();
        exists = false;
        for (String id : ids) {
            if (unknownId.equals(id)) {
                exists = true;
            }
        }
    } while (exists);
    for (boolean persistent : new boolean[] { true, false }) {
        assertThat("job with unknown id should return as expected", jobManager.getJobStatus(unknownId), is(JobStatus.UNKNOWN));
    }
    final CountDownLatch startLatch = new CountDownLatch(1), endLatch = new CountDownLatch(1);
    final DummyTwoLatchJob twoLatchJob = new DummyTwoLatchJob(new Params(0), startLatch, endLatch);
    jobManager.start();
    jobManager.addJob(twoLatchJob);
    final String jobId = twoLatchJob.getId();
    twoLatchJob.waitTillOnRun();
    final CountDownLatch twoLatchJobDone = new CountDownLatch(1);
    jobManager.addCallback(new JobManagerCallbackAdapter() {

        @Override
        public void onAfterJobRun(@NonNull Job job, int resultCode) {
            if (job == twoLatchJob && resultCode == RESULT_SUCCEED) {
                jobManager.removeCallback(this);
                twoLatchJobDone.countDown();
            }
        }
    });
    assertThat("job should be in running state", jobManager.getJobStatus(jobId), is(JobStatus.RUNNING));
    //let it run
    startLatch.countDown();
    try {
        //wait till it finishes
        endLatch.await();
    } catch (InterruptedException ignored) {
    }
    twoLatchJobDone.await(1, TimeUnit.MINUTES);
    assertThat("finished job should go to unknown state. id: " + jobId, jobManager.getJobStatus(jobId), is(JobStatus.UNKNOWN));
    //network requiring job should not be ready
    for (Integer i : networkRequiringJobIndices) {
        assertThat("network requiring job should still be not-ready", jobManager.getJobStatus(ids[i]), is(JobStatus.WAITING_NOT_READY));
    }
    jobManager.stop();
    networkUtil.setNetworkStatus(NetworkUtil.METERED, true);
    for (Integer i : networkRequiringJobIndices) {
        assertThat("network requiring job should still be ready after network is there", jobManager.getJobStatus(ids[i]), is(JobStatus.WAITING_READY));
    }
    final CountDownLatch networkRequiredLatch = new CountDownLatch(networkRequiringJobIndices.size());
    jobManager.addCallback(new JobManagerCallbackAdapter() {

        @Override
        public void onDone(@NonNull Job job) {
            if (job.getTags().contains(REQ_NETWORK_TAG)) {
                networkRequiredLatch.countDown();
            }
        }
    });
    jobManager.start();
    networkRequiredLatch.await(1, TimeUnit.MINUTES);
    assertThat("jobs should finish", jobManager.count(), is(0));
    for (int i = 0; i < jobs.length; i++) {
        //after all jobs finish, state should be unknown
        assertThat("all jobs finished, states should be unknown", jobManager.getJobStatus(ids[i]), is(JobStatus.UNKNOWN));
    }
    final long SHORT_SLEEP = 2000;
    Job[] delayedJobs = new Job[] { new DummyJob(new Params(0).delayInMs(SHORT_SLEEP)), new DummyJob(new Params(0).delayInMs(SHORT_SLEEP).persist()), new DummyJob(new Params(0).delayInMs(SHORT_SLEEP * 10)), new DummyJob(new Params(0).delayInMs(SHORT_SLEEP * 10).persist()) };
    String[] delayedIds = new String[delayedJobs.length];
    long start = mockTimer.nanoTime();
    for (int i = 0; i < delayedJobs.length; i++) {
        jobManager.addJob(delayedJobs[i]);
        delayedIds[i] = delayedJobs[i].getId();
    }
    for (int i = 0; i < delayedJobs.length; i++) {
        assertThat("delayed job(" + i + ") should receive not ready status. startMs:" + start, jobManager.getJobStatus(delayedIds[i]), is(JobStatus.WAITING_NOT_READY));
    }
    jobManager.stop();
    //sleep
    mockTimer.incrementMs(SHORT_SLEEP * 2);
    for (int i = 0; i < delayedJobs.length; i++) {
        if (delayedJobs[i].getDelayInMs() == SHORT_SLEEP) {
            assertThat("when enough time passes, delayed jobs should move to ready state", jobManager.getJobStatus(delayedIds[i]), is(JobStatus.WAITING_READY));
        } else {
            assertThat("delayed job should receive not ready status until their time comes", jobManager.getJobStatus(delayedIds[i]), is(JobStatus.WAITING_NOT_READY));
        }
    }
}
Also used : JobManagerCallbackAdapter(com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter) Configuration(com.birbit.android.jobqueue.config.Configuration) ArrayList(java.util.ArrayList) Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) CountDownLatch(java.util.concurrent.CountDownLatch) JobStatus(com.birbit.android.jobqueue.JobStatus) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Job(com.birbit.android.jobqueue.Job) Test(org.junit.Test) TargetApi(android.annotation.TargetApi)

Example 4 with JobManagerCallbackAdapter

use of com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter in project android-priority-jobqueue by yigit.

the class CountTest method testCount.

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Test
public void testCount() throws Exception {
    enableDebug();
    JobManager jobManager = createJobManager();
    jobManager.stop();
    for (int i = 0; i < 10; i++) {
        jobManager.addJob(new DummyJob(new Params(0).persist()));
        MatcherAssert.assertThat((int) jobManager.count(), equalTo(i * 2 + 1));
        jobManager.addJob(new DummyJob(new Params(0).persist()));
        MatcherAssert.assertThat((int) jobManager.count(), equalTo(i * 2 + 2));
    }
    final CountDownLatch jobsToRun = new CountDownLatch(20);
    jobManager.addCallback(new JobManagerCallbackAdapter() {

        @Override
        public void onAfterJobRun(@NonNull Job job, int resultCode) {
            if (resultCode == JobManagerCallback.RESULT_SUCCEED) {
                jobsToRun.countDown();
            }
        }
    });
    jobManager.start();
    MatcherAssert.assertThat("test sanity", jobsToRun.await(1, TimeUnit.MINUTES), is(true));
    MatcherAssert.assertThat((int) jobManager.count(), equalTo(0));
}
Also used : JobManagerCallbackAdapter(com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) CountDownLatch(java.util.concurrent.CountDownLatch) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) Job(com.birbit.android.jobqueue.Job) Test(org.junit.Test) TargetApi(android.annotation.TargetApi)

Example 5 with JobManagerCallbackAdapter

use of com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter in project android-priority-jobqueue by yigit.

the class JobManager method addJob.

/**
     * Adds the Job to the JobManager and waits until the add is handled.
     * <p>
     * You cannot call this method on the main thread because it may potentially block it for a long
     * time.
     *
     * Even if you are not on the main thread, you should prefer using
     * {@link #addJobInBackground(Job)} or {@link #addJobInBackground(Job, AsyncAddCallback)} if
     * you don't need to block your thread until the Job is actually added.
     *
     * @param job The Job to be added
     *
     * @see #addJobInBackground(Job)
     * @see #addJobInBackground(Job, AsyncAddCallback)
     */
public void addJob(Job job) {
    assertNotInMainThread("Cannot call this method on main thread. Use addJobInBackground " + "instead.");
    assertNotInJobManagerThread("Cannot call sync methods in JobManager's callback thread." + "Use addJobInBackground instead");
    final CountDownLatch latch = new CountDownLatch(1);
    final String uuid = job.getId();
    addCallback(new JobManagerCallbackAdapter() {

        @Override
        public void onJobAdded(@NonNull Job job) {
            if (uuid.equals(job.getId())) {
                latch.countDown();
                removeCallback(this);
            }
        }
    });
    addJobInBackground(job);
    try {
        latch.await();
    } catch (InterruptedException ignored) {
    }
}
Also used : JobManagerCallbackAdapter(com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

JobManagerCallbackAdapter (com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter)12 Job (com.birbit.android.jobqueue.Job)10 DummyJob (com.birbit.android.jobqueue.test.jobs.DummyJob)10 CountDownLatch (java.util.concurrent.CountDownLatch)10 TargetApi (android.annotation.TargetApi)8 JobManager (com.birbit.android.jobqueue.JobManager)8 Params (com.birbit.android.jobqueue.Params)8 Test (org.junit.Test)4 RetryConstraint (com.birbit.android.jobqueue.RetryConstraint)3 Configuration (com.birbit.android.jobqueue.config.Configuration)3 ArrayList (java.util.ArrayList)3 SuppressLint (android.annotation.SuppressLint)1 Pair (android.util.Pair)1 CallbackManager (com.birbit.android.jobqueue.CallbackManager)1 JobStatus (com.birbit.android.jobqueue.JobStatus)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 FutureTask (java.util.concurrent.FutureTask)1 Semaphore (java.util.concurrent.Semaphore)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1