Debian Codegraph @

core/java/android/os/PersistableBundle.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2014 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 android.os;
18
19 import static java.nio.charset.StandardCharsets.UTF_8;
20
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.util.ArrayMap;
24 import android.util.TypedXmlPullParser;
25 import android.util.TypedXmlSerializer;
26 import android.util.Xml;
27 import android.util.proto.ProtoOutputStream;
28
29 import com.android.internal.util.XmlUtils;
30
31 import org.xmlpull.v1.XmlPullParser;
32 import org.xmlpull.v1.XmlPullParserException;
33 import org.xmlpull.v1.XmlSerializer;
34
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.OutputStream;
38 import java.io.Serializable;
39 import java.util.ArrayList;
40
41 /**
42 * A mapping from String keys to values of various types. The set of types
43 * supported by this class is purposefully restricted to simple objects that can
44 * safely be persisted to and restored from disk.
45 *
46 * <p><b>Warning:</b> Note that {@link PersistableBundle} is a lazy container and as such it does
47 * NOT implement {@link #equals(Object)} or {@link #hashCode()}.
48 *
49 * @see Bundle
50 */
51 public final class PersistableBundle extends BaseBundle implements Cloneable, Parcelable,
52 XmlUtils.WriteMapCallback {
53 private static final String TAG_PERSISTABLEMAP = "pbundle_as_map";
54
55 /** An unmodifiable {@code PersistableBundle} that is always {@link #isEmpty() empty}. */
56 public static final PersistableBundle EMPTY;
57
58 static {
59 EMPTY = new PersistableBundle();
60 EMPTY.mMap = ArrayMap.EMPTY;
61 }
62
63 /** @hide */
64 public static boolean isValidType(Object value) {
65 return (value instanceof Integer) || (value instanceof Long) ||
66 (value instanceof Double) || (value instanceof String) ||
67 (value instanceof int[]) || (value instanceof long[]) ||
68 (value instanceof double[]) || (value instanceof String[]) ||
69 (value instanceof PersistableBundle) || (value == null) ||
70 (value instanceof Boolean) || (value instanceof boolean[]);
71 }
72
73 /**
74 * Constructs a new, empty PersistableBundle.
75 */
76 public PersistableBundle() {
77 super();
78 mFlags = FLAG_DEFUSABLE;
79 }
80
81 /**
82 * Constructs a new, empty PersistableBundle sized to hold the given number of
83 * elements. The PersistableBundle will grow as needed.
84 *
85 * @param capacity the initial capacity of the PersistableBundle
86 */
87 public PersistableBundle(int capacity) {
88 super(capacity);
89 mFlags = FLAG_DEFUSABLE;
90 }
91
92 /**
93 * Constructs a PersistableBundle containing a copy of the mappings from the given
94 * PersistableBundle. Does only a shallow copy of the original PersistableBundle -- see
95 * {@link #deepCopy()} if that is not what you want.
96 *
97 * @param b a PersistableBundle to be copied.
98 *
99 * @see #deepCopy()
100 */
101 public PersistableBundle(PersistableBundle b) {
102 super(b);
103 mFlags = b.mFlags;
104 }
105
106
107 /**
108 * Constructs a PersistableBundle from a Bundle. Does only a shallow copy of the Bundle.
109 *
110 * <p><b>Warning:</b> This method will deserialize every item on the bundle, including custom
111 * types such as {@link Parcelable} and {@link Serializable}, so only use this when you trust
112 * the source. Specifically don't use this method on app-provided bundles.
113 *
114 * @param b a Bundle to be copied.
115 *
116 * @throws IllegalArgumentException if any element of {@code b} cannot be persisted.
117 *
118 * @hide
119 */
120 public PersistableBundle(Bundle b) {
121 this(b.getItemwiseMap());
122 }
123
124 /**
125 * Constructs a PersistableBundle containing the mappings passed in.
126 *
127 * @param map a Map containing only those items that can be persisted.
128 * @throws IllegalArgumentException if any element of #map cannot be persisted.
129 */
130 private PersistableBundle(ArrayMap<String, Object> map) {
131 super();
132 mFlags = FLAG_DEFUSABLE;
133
134 // First stuff everything in.
135 putAll(map);
136
137 // Now verify each item throwing an exception if there is a violation.
138 final int N = mMap.size();
139 for (int i=0; i<N; i++) {
140 Object value = mMap.valueAt(i);
141 if (value instanceof ArrayMap) {
142 // Fix up any Maps by replacing them with PersistableBundles.
143 mMap.setValueAt(i, new PersistableBundle((ArrayMap<String, Object>) value));
144 } else if (value instanceof Bundle) {
145 mMap.setValueAt(i, new PersistableBundle(((Bundle) value)));
146 } else if (!isValidType(value)) {
147 throw new IllegalArgumentException("Bad value in PersistableBundle key="
148 + mMap.keyAt(i) + " value=" + value);
149 }
150 }
151 }
152
153 /* package */ PersistableBundle(Parcel parcelledData, int length) {
154 super(parcelledData, length);
155 mFlags = FLAG_DEFUSABLE;
156 }
157
158 /**
159 * Constructs a {@link PersistableBundle} containing a copy of {@code from}.
160 *
161 * @param from The bundle to be copied.
162 * @param deep Whether is a deep or shallow copy.
163 *
164 * @hide
165 */
166 PersistableBundle(PersistableBundle from, boolean deep) {
167 super(from, deep);
168 }
169
170 /**
171 * Make a PersistableBundle for a single key/value pair.
172 *
173 * @hide
174 */
175 public static PersistableBundle forPair(String key, String value) {
176 PersistableBundle b = new PersistableBundle(1);
177 b.putString(key, value);
178 return b;
179 }
180
181 /**
182 * Clones the current PersistableBundle. The internal map is cloned, but the keys and
183 * values to which it refers are copied by reference.
184 */
185 @Override
186 public Object clone() {
187 return new PersistableBundle(this);
188 }
189
190 /**
191 * Make a deep copy of the given bundle. Traverses into inner containers and copies
192 * them as well, so they are not shared across bundles. Will traverse in to
193 * {@link Bundle}, {@link PersistableBundle}, {@link ArrayList}, and all types of
194 * primitive arrays. Other types of objects (such as Parcelable or Serializable)
195 * are referenced as-is and not copied in any way.
196 */
197 public PersistableBundle deepCopy() {
198 return new PersistableBundle(this, /* deep */ true);
199 }
200
201 /**
202 * Inserts a PersistableBundle value into the mapping of this Bundle, replacing
203 * any existing value for the given key. Either key or value may be null.
204 *
205 * @param key a String, or null
206 * @param value a Bundle object, or null
207 */
208 public void putPersistableBundle(@Nullable String key, @Nullable PersistableBundle value) {
209 unparcel();
210 mMap.put(key, value);
211 }
212
213 /**
214 * Returns the value associated with the given key, or null if
215 * no mapping of the desired type exists for the given key or a null
216 * value is explicitly associated with the key.
217 *
218 * @param key a String, or null
219 * @return a Bundle value, or null
220 */
221 @Nullable
222 public PersistableBundle getPersistableBundle(@Nullable String key) {
223 unparcel();
224 Object o = mMap.get(key);
225 if (o == null) {
226 return null;
227 }
228 try {
229 return (PersistableBundle) o;
230 } catch (ClassCastException e) {
231 typeWarning(key, o, "Bundle", e);
232 return null;
233 }
234 }
235
236 public static final @android.annotation.NonNull Parcelable.Creator<PersistableBundle> CREATOR =
237 new Parcelable.Creator<PersistableBundle>() {
238 @Override
239 public PersistableBundle createFromParcel(Parcel in) {
240 return in.readPersistableBundle();
241 }
242
243 @Override
244 public PersistableBundle[] newArray(int size) {
245 return new PersistableBundle[size];
246 }
247 };
248
249 /** @hide */
250 @Override
251 public void writeUnknownObject(Object v, String name, TypedXmlSerializer out)
252 throws XmlPullParserException, IOException {
253 if (v instanceof PersistableBundle) {
254 out.startTag(null, TAG_PERSISTABLEMAP);
255 out.attribute(null, "name", name);
256 ((PersistableBundle) v).saveToXml(out);
257 out.endTag(null, TAG_PERSISTABLEMAP);
258 } else {
259 throw new XmlPullParserException("Unknown Object o=" + v);
260 }
261 }
262
263 /** @hide */
264 public void saveToXml(XmlSerializer out) throws IOException, XmlPullParserException {
265 saveToXml(XmlUtils.makeTyped(out));
266 }
267
268 /** @hide */
269 public void saveToXml(TypedXmlSerializer out) throws IOException, XmlPullParserException {
270 unparcel();
271 XmlUtils.writeMapXml(mMap, out, this);
272 }
273
274 /** @hide */
275 static class MyReadMapCallback implements XmlUtils.ReadMapCallback {
276 @Override
277 public Object readThisUnknownObjectXml(TypedXmlPullParser in, String tag)
278 throws XmlPullParserException, IOException {
279 if (TAG_PERSISTABLEMAP.equals(tag)) {
280 return restoreFromXml(in);
281 }
282 throw new XmlPullParserException("Unknown tag=" + tag);
283 }
284 }
285
286 /**
287 * Report the nature of this Parcelable's contents
288 */
289 @Override
290 public int describeContents() {
291 return 0;
292 }
293
294 /**
295 * Writes the PersistableBundle contents to a Parcel, typically in order for
296 * it to be passed through an IBinder connection.
297 * @param parcel The parcel to copy this bundle to.
298 */
299 @Override
300 public void writeToParcel(Parcel parcel, int flags) {
301 final boolean oldAllowFds = parcel.pushAllowFds(false);
302 try {
303 writeToParcelInner(parcel, flags);
304 } finally {
305 parcel.restoreAllowFds(oldAllowFds);
306 }
307 }
308
309 /** @hide */
310 public static PersistableBundle restoreFromXml(XmlPullParser in) throws IOException,
311 XmlPullParserException {
312 return restoreFromXml(XmlUtils.makeTyped(in));
313 }
314
315 /** @hide */
316 public static PersistableBundle restoreFromXml(TypedXmlPullParser in) throws IOException,
317 XmlPullParserException {
318 final int outerDepth = in.getDepth();
319 final String startTag = in.getName();
320 final String[] tagName = new String[1];
321 int event;
322 while (((event = in.next()) != XmlPullParser.END_DOCUMENT) &&
323 (event != XmlPullParser.END_TAG || in.getDepth() < outerDepth)) {
324 if (event == XmlPullParser.START_TAG) {
325 return new PersistableBundle((ArrayMap<String, Object>)
326 XmlUtils.readThisArrayMapXml(in, startTag, tagName,
327 new MyReadMapCallback()));
328 }
329 }
330 return new PersistableBundle(); // An empty mutable PersistableBundle
331 }
332
333 /**
334 * Returns a string representation of the {@link PersistableBundle} that may be suitable for
335 * debugging. It won't print the internal map if its content hasn't been unparcelled.
336 */
337 @Override
338 public synchronized String toString() {
339 if (mParcelledData != null) {
340 if (isEmptyParcel()) {
341 return "PersistableBundle[EMPTY_PARCEL]";
342 } else {
343 return "PersistableBundle[mParcelledData.dataSize=" +
344 mParcelledData.dataSize() + "]";
345 }
346 }
347 return "PersistableBundle[" + mMap.toString() + "]";
348 }
349
350 /** @hide */
351 synchronized public String toShortString() {
352 if (mParcelledData != null) {
353 if (isEmptyParcel()) {
354 return "EMPTY_PARCEL";
355 } else {
356 return "mParcelledData.dataSize=" + mParcelledData.dataSize();
357 }
358 }
359 return mMap.toString();
360 }
361
362 /** @hide */
363 public void dumpDebug(ProtoOutputStream proto, long fieldId) {
364 final long token = proto.start(fieldId);
365
366 if (mParcelledData != null) {
367 if (isEmptyParcel()) {
368 proto.write(PersistableBundleProto.PARCELLED_DATA_SIZE, 0);
369 } else {
370 proto.write(PersistableBundleProto.PARCELLED_DATA_SIZE, mParcelledData.dataSize());
371 }
372 } else {
373 proto.write(PersistableBundleProto.MAP_DATA, mMap.toString());
374 }
375
376 proto.end(token);
377 }
378
379 /**
380 * Writes the content of the {@link PersistableBundle} to a {@link OutputStream}.
381 *
382 * <p>The content can be read by a {@link #readFromStream}.
383 *
384 * @see #readFromStream
385 */
386 public void writeToStream(@NonNull OutputStream outputStream) throws IOException {
387 TypedXmlSerializer serializer = Xml.newFastSerializer();
388 serializer.setOutput(outputStream, UTF_8.name());
389 serializer.startTag(null, "bundle");
390 try {
391 saveToXml(serializer);
392 } catch (XmlPullParserException e) {
393 throw new IOException(e);
394 }
395 serializer.endTag(null, "bundle");
396 serializer.flush();
397 }
398
399 /**
400 * Reads a {@link PersistableBundle} from an {@link InputStream}.
401 *
402 * <p>The stream must be generated by {@link #writeToStream}.
403 *
404 * @see #writeToStream
405 */
406 @NonNull
407 public static PersistableBundle readFromStream(@NonNull InputStream inputStream)
408 throws IOException {
409 try {
410 TypedXmlPullParser parser = Xml.newFastPullParser();
411 parser.setInput(inputStream, UTF_8.name());
412 parser.next();
413 return PersistableBundle.restoreFromXml(parser);
414 } catch (XmlPullParserException e) {
415 throw new IOException(e);
416 }
417 }
418 }