1 /*
2  * Copyright (C) 2015 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.ahat;
18 
19 import com.android.ahat.heapdump.AhatSnapshot;
20 import com.android.tools.perflib.heap.ProguardMap;
21 import com.android.tools.perflib.heap.hprof.Hprof;
22 import com.android.tools.perflib.heap.hprof.HprofRecord;
23 import com.android.tools.perflib.heap.hprof.HprofStringBuilder;
24 import com.android.tools.perflib.heap.io.InMemoryBuffer;
25 import java.io.ByteArrayOutputStream;
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.Date;
29 import java.util.List;
30 
31 /**
32  * Class with utilities to help constructing snapshots for tests.
33  */
34 public class SnapshotBuilder {
35 
36   // Helper function to make a snapshot with id size 4 given an
37   // HprofStringBuilder and list of HprofRecords
makeSnapshot(HprofStringBuilder strings, List<HprofRecord> records)38   public static AhatSnapshot makeSnapshot(HprofStringBuilder strings, List<HprofRecord> records)
39     throws IOException {
40     // TODO: When perflib can handle the case where strings are referred to
41     // before they are defined, just add the string records to the records
42     // list.
43     List<HprofRecord> actualRecords = new ArrayList<HprofRecord>();
44     actualRecords.addAll(strings.getStringRecords());
45     actualRecords.addAll(records);
46 
47     Hprof hprof = new Hprof("JAVA PROFILE 1.0.3", 4, new Date(), actualRecords);
48     ByteArrayOutputStream os = new ByteArrayOutputStream();
49     hprof.write(os);
50     InMemoryBuffer buffer = new InMemoryBuffer(os.toByteArray());
51     return AhatSnapshot.fromDataBuffer(buffer, new ProguardMap());
52   }
53 }
54