1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License
15  */
16 
17 package com.android.voicemail.impl.scheduling;
18 
19 import android.content.Context;
20 import android.os.Bundle;
21 import android.support.annotation.NonNull;
22 import android.support.annotation.Nullable;
23 import com.android.voicemail.impl.Assert;
24 import com.android.voicemail.impl.VvmLog;
25 import com.android.voicemail.impl.scheduling.Task.TaskId;
26 import com.android.voicemail.impl.scheduling.Tasks.TaskCreationException;
27 import java.util.ArrayDeque;
28 import java.util.ArrayList;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Queue;
32 
33 /**
34  * A queue that manages priority and duplication of {@link Task}. A task is identified by a {@link
35  * TaskId}, which consists of an integer representing the operation the task, and a {@link
36  * android.telecom.PhoneAccountHandle} representing which SIM it is operated on.
37  */
38 class TaskQueue implements Iterable<Task> {
39 
40   private final Queue<Task> queue = new ArrayDeque<>();
41 
toBundles()42   public List<Bundle> toBundles() {
43     List<Bundle> result = new ArrayList<>(queue.size());
44     for (Task task : queue) {
45       result.add(Tasks.toBundle(task));
46     }
47     return result;
48   }
49 
fromBundles(Context context, List<Bundle> pendingTasks)50   public void fromBundles(Context context, List<Bundle> pendingTasks) {
51     Assert.isTrue(queue.isEmpty());
52     for (Bundle pendingTask : pendingTasks) {
53       try {
54         Task task = Tasks.createTask(context, pendingTask);
55         task.onRestore(pendingTask);
56         add(task);
57       } catch (TaskCreationException e) {
58         VvmLog.e("TaskQueue.fromBundles", "cannot create task", e);
59       }
60     }
61   }
62 
63   /**
64    * Add a new task to the queue. A new task with a TaskId collision will be discarded, and {@link
65    * Task#onDuplicatedTaskAdded(Task)} will be called on the existing task.
66    *
67    * @return {@code true} if the task is added, or {@code false} if the task is discarded due to
68    *     collision.
69    */
add(Task task)70   public boolean add(Task task) {
71     if (task.getId().id == Task.TASK_INVALID) {
72       throw new AssertionError("Task id was not set to a valid value before adding.");
73     }
74     if (task.getId().id != Task.TASK_ALLOW_DUPLICATES) {
75       Task oldTask = getTask(task.getId());
76       if (oldTask != null) {
77         oldTask.onDuplicatedTaskAdded(task);
78         VvmLog.i("TaskQueue.add", "duplicated task added");
79         return false;
80       }
81     }
82     queue.add(task);
83     return true;
84   }
85 
remove(Task task)86   public void remove(Task task) {
87     queue.remove(task);
88   }
89 
getTask(TaskId id)90   public Task getTask(TaskId id) {
91     Assert.isMainThread();
92     for (Task task : queue) {
93       if (task.getId().equals(id)) {
94         return task;
95       }
96     }
97     return null;
98   }
99 
100   /**
101    * Packed return value of {@link #getNextTask(long)}. If a runnable task is found {@link
102    * #minimalWaitTimeMillis} will be {@code null}. If no tasks is runnable {@link #task} will be
103    * {@code null}, and {@link #minimalWaitTimeMillis} will contain the time to wait. If there are no
104    * tasks at all both will be {@code null}.
105    */
106   static final class NextTask {
107     @Nullable final Task task;
108     @Nullable final Long minimalWaitTimeMillis;
109 
NextTask(@ullable Task task, @Nullable Long minimalWaitTimeMillis)110     NextTask(@Nullable Task task, @Nullable Long minimalWaitTimeMillis) {
111       this.task = task;
112       this.minimalWaitTimeMillis = minimalWaitTimeMillis;
113     }
114   }
115 
116   /**
117    * The next task is the first task with {@link Task#getReadyInMilliSeconds()} return a value less
118    * then {@code readyToleranceMillis}, in insertion order. If no task matches this criteria, the
119    * minimal value of {@link Task#getReadyInMilliSeconds()} is returned instead. If there are no
120    * tasks at all, the minimalWaitTimeMillis will also be null.
121    */
122   @NonNull
getNextTask(long readyToleranceMillis)123   NextTask getNextTask(long readyToleranceMillis) {
124     Long minimalWaitTime = null;
125     for (Task task : queue) {
126       long waitTime = task.getReadyInMilliSeconds();
127       if (waitTime < readyToleranceMillis) {
128         return new NextTask(task, 0L);
129       } else {
130         if (minimalWaitTime == null || waitTime < minimalWaitTime) {
131           minimalWaitTime = waitTime;
132         }
133       }
134     }
135     return new NextTask(null, minimalWaitTime);
136   }
137 
clear()138   public void clear() {
139     queue.clear();
140   }
141 
size()142   public int size() {
143     return queue.size();
144   }
145 
isEmpty()146   public boolean isEmpty() {
147     return queue.isEmpty();
148   }
149 
150   @Override
iterator()151   public Iterator<Task> iterator() {
152     return queue.iterator();
153   }
154 }
155