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 23 import java.io.File; 24 import java.io.FileInputStream; 25 import java.io.IOException; 26 import java.io.InputStream; 27 28 /** Utility to read the {@link TestRecord} proto from a file. */ 29 public class TestRecordProtoUtil { 30 31 /** 32 * Pick a 4MB default size to allow the buffer to grow for big protobuf. The default value could 33 * fail in some cases. 34 */ 35 private static final int DEFAULT_SIZE_BYTES = 4 * 1024 * 1024; 36 37 /** 38 * Read {@link TestRecord} from a file and return it. 39 * 40 * @param protoFile The {@link File} containing the record 41 * @return a {@link TestRecord} created from the file. 42 * @throws IOException, InvalidProtocolBufferException 43 */ readFromFile(File protoFile)44 public static TestRecord readFromFile(File protoFile) throws IOException { 45 return readFromFile(protoFile, true); 46 } 47 48 /** 49 * Read {@link TestRecord} from a file and return it. 50 * 51 * @param protoFile The {@link File} containing the record 52 * @param readDelimited True if the proto file in delimited format. False if the file is default 53 * format. 54 * @throws IOException, InvalidProtocolBufferException 55 */ readFromFile(File protoFile, boolean readDelimited)56 public static TestRecord readFromFile(File protoFile, boolean readDelimited) 57 throws IOException { 58 TestRecord record = null; 59 try (InputStream stream = new FileInputStream(protoFile)) { 60 CodedInputStream is = CodedInputStream.newInstance(stream); 61 if (readDelimited) { 62 is.setSizeLimit(Integer.MAX_VALUE); 63 ByteArrayList data = new ByteArrayList(DEFAULT_SIZE_BYTES); 64 while (!is.isAtEnd()) { 65 int size = is.readRawVarint32(); 66 byte[] dataByte = is.readRawBytes(size); 67 data.addAll(dataByte); 68 } 69 record = TestRecord.parseFrom(data.getContents()); 70 data.clear(); 71 } else { 72 record = TestRecord.parseFrom(is); 73 } 74 } 75 return record; 76 } 77 } 78