• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 package ohos.devtools.services.hiperf;
16 
17 import java.io.File;
18 import java.io.FileInputStream;
19 import java.io.IOException;
20 import java.nio.ByteBuffer;
21 import java.nio.ByteOrder;
22 import java.nio.MappedByteBuffer;
23 import java.nio.channels.FileChannel;
24 import java.nio.charset.StandardCharsets;
25 
26 /**
27  * ParsePerf Parent Class.
28  *
29  * @since 2021/9/20
30  */
31 public abstract class ParsePerf {
32 
33     /**
34      * insertSample to db
35      */
insertSample()36     public abstract void insertSample();
37 
38     /**
39      * parseFile parse perf.trace file
40      *
41      * @param file proto buf file
42      * @throws IOException read Exception
43      */
parseFile(File file)44     public abstract void parseFile(File file) throws IOException;
45 
46     /**
47      * read File to ByteBuffer
48      *
49      * @param file trace file
50      * @return ByteBuffer
51      * @throws IOException read Exception
52      */
byteBufferFromFile(File file)53     protected ByteBuffer byteBufferFromFile(File file) throws IOException {
54         try (FileInputStream dataFile = new FileInputStream(file)) {
55             MappedByteBuffer buffer = dataFile.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
56             buffer.order(ByteOrder.LITTLE_ENDIAN);
57             return buffer;
58         }
59     }
60 
61     /**
62      * verify Head judge file is correct
63      *
64      * @param buffer ByteBuffer
65      * @param head Verify Head
66      */
verifyHead(ByteBuffer buffer, String head)67     protected void verifyHead(ByteBuffer buffer, String head) {
68         byte[] sign = new byte[head.length()];
69         buffer.get(sign);
70         if (!(new String(sign, StandardCharsets.UTF_8)).equals(head)) {
71             throw new IllegalStateException("perf trace could not be parsed due to magic number mismatch.");
72         }
73     }
74 }
75