• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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 package com.android.tradefed.util.proto;
17 
18 import com.android.tradefed.result.proto.TestRecordProto.TestRecord;
19 import com.android.tradefed.util.ByteArrayList;
20 
21 import com.google.protobuf.CodedInputStream;
22 import com.google.protobuf.InvalidProtocolBufferException;
23 
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 
29 /** Utility to read the {@link TestRecord} proto from a file. */
30 public class TestRecordProtoUtil {
31 
32     /**
33      * Pick a 4MB default size to allow the buffer to grow for big protobuf. The default value could
34      * fail in some cases.
35      */
36     private static final int DEFAULT_SIZE_BYTES = 4 * 1024 * 1024;
37 
38     /**
39      * Read {@link TestRecord} from a file and return it.
40      *
41      * @param protoFile The {@link File} containing the record
42      * @return a {@link TestRecord} created from the file.
43      * @throws IOException, InvalidProtocolBufferException
44      */
readFromFile(File protoFile)45     public static TestRecord readFromFile(File protoFile)
46             throws IOException, InvalidProtocolBufferException {
47         TestRecord record = null;
48         try (InputStream stream = new FileInputStream(protoFile)) {
49             CodedInputStream is = CodedInputStream.newInstance(stream);
50             is.setSizeLimit(Integer.MAX_VALUE);
51             ByteArrayList data = new ByteArrayList(DEFAULT_SIZE_BYTES);
52             while (!is.isAtEnd()) {
53                 int size = is.readRawVarint32();
54                 byte[] dataByte = is.readRawBytes(size);
55                 data.addAll(dataByte);
56             }
57             record = TestRecord.parseFrom(data.getContents());
58             data.clear();
59         }
60         return record;
61     }
62 }
63