• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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.eventlib;
18 
19 import java.io.ByteArrayInputStream;
20 import java.io.ByteArrayOutputStream;
21 import java.io.IOException;
22 import java.io.ObjectInput;
23 import java.io.ObjectInputStream;
24 import java.io.ObjectOutputStream;
25 import java.io.Serializable;
26 import java.time.Instant;
27 
28 /**
29  * Represents a single action which has been logged.
30  */
31 public abstract class Event implements Serializable {
32 
33     private static final long serialVersionUID = 1;
34 
35     // This class should contain all standard data applicable to all Events.
36 
37     protected String mPackageName;
38     protected Instant mTimestamp;
39 
40     /** Get the package name this event was logged by. */
packageName()41     public String packageName() {
42         return mPackageName;
43     }
44 
45     /** Get the time that this event was logged. */
timestamp()46     public Instant timestamp() {
47         return mTimestamp;
48     }
49 
50     /**
51      * Serialize the {@link Event} to a byte array.
52      *
53      * <p>The resulting array can be deserialized using {@link #fromBytes(byte[])}.
54      */
toBytes()55     byte[] toBytes() throws IOException {
56         try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
57              ObjectOutputStream out = new ObjectOutputStream(bos)) {
58             out.writeObject(this);
59             out.flush();
60             return bos.toByteArray();
61         }
62     }
63 
64     /**
65      * Deserialize an {@link Event} from a byte array created using {@link #toBytes()}.
66      */
fromBytes(byte[] bytes)67     static Event fromBytes(byte[] bytes) throws IOException {
68         try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
69              ObjectInput in = new ObjectInputStream(bis)) {
70             try {
71                 return (Event) in.readObject();
72             } catch (ClassNotFoundException e) {
73                 throw new IllegalStateException(
74                         "Trying to read Event which is not on classpath", e);
75             }
76         }
77     }
78 }
79