Search in sources :

Example 1 with Job

use of com.birbit.android.jobqueue.Job 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 Job

use of com.birbit.android.jobqueue.Job 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 Job

use of com.birbit.android.jobqueue.Job 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 Job

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

the class AssertThreadsTest method assertFailure.

private void assertFailure(final Runnable runnable) throws InterruptedException {
    final Throwable[] throwable = new Throwable[1];
    jobManager = createJobManager();
    final DummyJob dummyJob = new DummyJob(new Params(0)) {

        @Override
        public void onAdded() {
            super.onAdded();
            try {
                runnable.run();
            } catch (Throwable t) {
                throwable[0] = t;
            }
        }
    };
    waitUntilAJobIsDone(jobManager, new WaitUntilCallback() {

        @Override
        public void run() {
            jobManager.addJob(dummyJob);
        }

        @Override
        public void assertJob(Job job) {
        }
    });
    assertThat(throwable[0] instanceof WrongThreadException, is(true));
}
Also used : DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob) WrongThreadException(com.birbit.android.jobqueue.WrongThreadException) Params(com.birbit.android.jobqueue.Params) Job(com.birbit.android.jobqueue.Job) DummyJob(com.birbit.android.jobqueue.test.jobs.DummyJob)

Example 5 with Job

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

the class CallbackTest method cancelViaShouldReRun.

@Test
public void cancelViaShouldReRun() throws Throwable {
    JobManagerCallback callback = mock(JobManagerCallback.class);
    final PublicJob job = spy(new PublicJob(new Params(0)));
    doNothing().when(job).onAdded();
    doThrow(new Exception()).when(job).onRun();
    doReturn(3).when(job).getRetryLimit();
    doReturn(RetryConstraint.CANCEL).when(job).shouldReRunOnThrowable(any(Throwable.class), anyInt(), anyInt());
    final JobManager jobManager = createJobManager();
    jobManager.addCallback(callback);
    waitUntilAJobIsDone(jobManager, new WaitUntilCallback() {

        @Override
        public void run() {
            jobManager.addJob(job);
        }

        @Override
        public void assertJob(Job job) {
        }
    });
    verify(callback).onJobAdded(job);
    verify(callback, times(1)).onJobRun(job, JobManagerCallback.RESULT_CANCEL_CANCELLED_VIA_SHOULD_RE_RUN);
    verify(callback).onJobCancelled(eq(job), eq(false), any(Throwable.class));
}
Also used : Params(com.birbit.android.jobqueue.Params) JobManager(com.birbit.android.jobqueue.JobManager) Job(com.birbit.android.jobqueue.Job) JobManagerCallback(com.birbit.android.jobqueue.callback.JobManagerCallback) Test(org.junit.Test)

Aggregations

Job (com.birbit.android.jobqueue.Job)36 Params (com.birbit.android.jobqueue.Params)31 JobManager (com.birbit.android.jobqueue.JobManager)26 DummyJob (com.birbit.android.jobqueue.test.jobs.DummyJob)26 Test (org.junit.Test)21 CountDownLatch (java.util.concurrent.CountDownLatch)19 TargetApi (android.annotation.TargetApi)10 JobManagerCallbackAdapter (com.birbit.android.jobqueue.callback.JobManagerCallbackAdapter)10 RetryConstraint (com.birbit.android.jobqueue.RetryConstraint)9 Configuration (com.birbit.android.jobqueue.config.Configuration)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 JobHolder (com.birbit.android.jobqueue.JobHolder)4 JobManagerCallback (com.birbit.android.jobqueue.callback.JobManagerCallback)4 ArrayList (java.util.ArrayList)4 CancelResult (com.birbit.android.jobqueue.CancelResult)3 SuppressLint (android.annotation.SuppressLint)2 NonNull (android.support.annotation.NonNull)2 SqliteJobQueue (com.birbit.android.jobqueue.persistentQueue.sqlite.SqliteJobQueue)2 Nullable (android.support.annotation.Nullable)1 Pair (android.util.Pair)1