• 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 
16 package ohos.devtools.datasources.utils.common.util;
17 
18 import java.io.ByteArrayInputStream;
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.ObjectInputStream;
22 import java.io.ObjectOutputStream;
23 import java.io.Serializable;
24 import java.lang.reflect.Field;
25 import java.lang.reflect.InvocationTargetException;
26 import java.lang.reflect.Method;
27 import java.lang.reflect.Type;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Locale;
32 import java.util.Map;
33 import java.util.Optional;
34 
35 import ohos.devtools.datasources.transport.grpc.service.HilogPluginConfig;
36 import ohos.devtools.datasources.transport.grpc.service.HiperfCallPluginConfigOuterClass;
37 import ohos.devtools.datasources.transport.grpc.service.MemoryPluginConfig;
38 import ohos.devtools.datasources.utils.profilerlog.ProfilerLogManager;
39 import org.apache.logging.log4j.LogManager;
40 import org.apache.logging.log4j.Logger;
41 
42 import com.google.protobuf.CodedOutputStream;
43 
44 import ohos.devtools.datasources.transport.grpc.service.BytracePluginConfigOuterClass;
45 import ohos.devtools.datasources.transport.grpc.service.TracePluginConfigOuterClass;
46 import ohos.devtools.views.common.LayoutConstants;
47 
48 /**
49  * Bean object utilities class.
50  *
51  * @since 2021/5/19 16:39
52  */
53 public class BeanUtil {
54     private static final Logger LOGGER = LogManager.getLogger(BeanUtil.class);
55 
56     /**
57      * Serializes object data.
58      *
59      * @param <T> <T>
60      * @param data Indicates the data to be deserialized.
61      * @return byte[]
62      */
serialize(T data)63     public static <T> byte[] serialize(T data) {
64         if (ProfilerLogManager.isInfoEnabled()) {
65             LOGGER.info("serialize");
66         }
67         byte[] dataArray = null;
68         // 1. Create an OutputStream object.
69         // 2. Create an OutputStream wrapper object named ObjectOutputStream,
70         // with the object wwritten to the OutputStream.
71         try (ByteArrayOutputStream outPutStream = new ByteArrayOutputStream();
72             ObjectOutputStream objectOutputStream = new ObjectOutputStream(outPutStream)) {
73             // 3. Write the object to OutputStream.
74             objectOutputStream.writeObject(data);
75             // 4. Convert OutputStream to a byte array.
76             dataArray = outPutStream.toByteArray();
77         } catch (IOException exception) {
78             if (ProfilerLogManager.isErrorEnabled()) {
79                 LOGGER.error("exception error {}", exception.getMessage());
80             }
81         }
82         return dataArray;
83     }
84 
85     /**
86      * Serialize data by code output stream.
87      *
88      * @param config Indicates the configuration data.
89      * @return Returns a byte array.
90      */
serializeByCodedOutPutStream(TracePluginConfigOuterClass.TracePluginConfig config)91     public static byte[] serializeByCodedOutPutStream(TracePluginConfigOuterClass.TracePluginConfig config) {
92         if (ProfilerLogManager.isInfoEnabled()) {
93             LOGGER.info("serializeByCodedOutPutStream");
94         }
95         byte[] dataArray = null;
96         try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
97             CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream);
98             config.writeTo(codedOutputStream);
99             codedOutputStream.flush();
100             dataArray = outputStream.toByteArray();
101         } catch (IOException exception) {
102             if (ProfilerLogManager.isErrorEnabled()) {
103                 LOGGER.error("exception error {}", exception.getMessage());
104             }
105         }
106         return dataArray;
107     }
108 
109     /**
110      * Serialize data by code output stream.
111      *
112      * @param config Indicates the configuration data.
113      * @return Returns a byte array.
114      */
serializeByCodedOutPutStream(HiperfCallPluginConfigOuterClass.HiperfCallPluginConfig config)115     public static byte[] serializeByCodedOutPutStream(HiperfCallPluginConfigOuterClass.HiperfCallPluginConfig config) {
116         if (ProfilerLogManager.isInfoEnabled()) {
117             LOGGER.info("serializeByCodedOutPutStream");
118         }
119         byte[] dataArray = null;
120         try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
121             CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream);
122             config.writeTo(codedOutputStream);
123             codedOutputStream.flush();
124             dataArray = outputStream.toByteArray();
125         } catch (IOException exception) {
126             if (ProfilerLogManager.isErrorEnabled()) {
127                 LOGGER.error("exception error {}", exception.getMessage());
128             }
129         }
130         return dataArray;
131     }
132 
133     /**
134      * Serialize data by code output stream.
135      *
136      * @param config Indicates the configuration data.
137      * @return Returns a byte array.
138      */
serializeByCodedOutPutStream(MemoryPluginConfig.MemoryConfig config)139     public static byte[] serializeByCodedOutPutStream(MemoryPluginConfig.MemoryConfig config) {
140         if (ProfilerLogManager.isInfoEnabled()) {
141             LOGGER.info("serializeByCodedOutPutStream");
142         }
143         byte[] dataArray = null;
144         try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
145             CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream);
146             config.writeTo(codedOutputStream);
147             codedOutputStream.flush();
148             dataArray = outputStream.toByteArray();
149         } catch (IOException exception) {
150             if (ProfilerLogManager.isErrorEnabled()) {
151                 LOGGER.error("exception error {}", exception.getMessage());
152             }
153         }
154         return dataArray;
155     }
156 
157     /**
158      * Serialize data by code output stream.
159      *
160      * @param config Indicates the configuration data.
161      * @return Returns a byte array.
162      */
serializeByCodedOutPutStream(HilogPluginConfig.HilogConfig config)163     public static byte[] serializeByCodedOutPutStream(HilogPluginConfig.HilogConfig config) {
164         if (ProfilerLogManager.isInfoEnabled()) {
165             LOGGER.info("serializeByCodedOutPutStream");
166         }
167         byte[] dataArray = null;
168         try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
169             CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream);
170             config.writeTo(codedOutputStream);
171             codedOutputStream.flush();
172             dataArray = outputStream.toByteArray();
173         } catch (IOException exception) {
174             if (ProfilerLogManager.isErrorEnabled()) {
175                 LOGGER.error("exception error {}", exception.getMessage());
176             }
177         }
178         return dataArray;
179     }
180 
181     /**
182      * Serialize by code output stream.
183      *
184      * @param config Indicates the configuration data.
185      * @return Returns a byte array.
186      */
serializeByCodedOutPutStream(BytracePluginConfigOuterClass.BytracePluginConfig config)187     public static byte[] serializeByCodedOutPutStream(BytracePluginConfigOuterClass.BytracePluginConfig config) {
188         if (ProfilerLogManager.isInfoEnabled()) {
189             LOGGER.info("serializeByCodedOutPutStream");
190         }
191         byte[] dataArray = null;
192         com.google.protobuf.CodedOutputStream codedOutputStream = null;
193         try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
194             codedOutputStream = CodedOutputStream.newInstance(outputStream, config.getSerializedSize());
195             config.writeTo(codedOutputStream);
196             codedOutputStream.flush();
197             dataArray = outputStream.toByteArray();
198         } catch (IOException exception) {
199             if (ProfilerLogManager.isErrorEnabled()) {
200                 LOGGER.error("exception error {}", exception.getMessage());
201             }
202         }
203         return dataArray;
204     }
205 
206     /**
207      * Deserializes object data.
208      *
209      * @param data Indicates the data to be deserialized.
210      * @return Object Returns the object value.
211      */
deserialize(byte[] data)212     public static Object deserialize(byte[] data) {
213         if (ProfilerLogManager.isInfoEnabled()) {
214             LOGGER.info("deserialize");
215         }
216         Object object = null;
217         try (ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
218             ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) {
219             object = objectInputStream.readObject();
220         } catch (IOException | ClassNotFoundException exception) {
221             if (ProfilerLogManager.isErrorEnabled()) {
222                 LOGGER.error("exception error {}", exception.getMessage());
223             }
224         }
225         return object;
226     }
227 
228     /**
229      * Get Fields information.
230      *
231      * @param <T> <T>
232      * @param obj Indicates the object.
233      * @return List Map
234      */
getFieldsInfo(T obj)235     public static <T> List<Map> getFieldsInfo(T obj) {
236         if (ProfilerLogManager.isInfoEnabled()) {
237             LOGGER.info("getFieldsInfo");
238         }
239         Field[] fields = obj.getClass().getDeclaredFields();
240         List list = new ArrayList();
241         Map infoMap = null;
242         for (int index = 0; index < fields.length; index++) {
243             infoMap = new HashMap(CommonUtil.collectionSize(LayoutConstants.SIXTEEN));
244             infoMap.put("type", fields[index].getType().toString());
245             Optional<Object> fieldName = getFieldValueByName(fields[index].getName(), obj);
246             if (fieldName.isPresent()) {
247                 infoMap.put(fields[index].getName(), fieldName.get());
248             }
249             list.add(infoMap);
250         }
251         return list;
252     }
253 
254     /**
255      * Returns a list of filed values.
256      *
257      * @param <T> <T>
258      * @param obj Indicates the object.
259      * @return List Map
260      */
getFields(T obj)261     public static <T> List<Map<String, Object>> getFields(T obj) {
262         if (ProfilerLogManager.isInfoEnabled()) {
263             LOGGER.info("getFields");
264         }
265         Field[] fields = obj.getClass().getDeclaredFields();
266         List list = new ArrayList();
267         Map infoMap = null;
268         for (int index = 0; index < fields.length; index++) {
269             infoMap = new HashMap(CommonUtil.collectionSize(LayoutConstants.SIXTEEN));
270             infoMap.put("type", fields[index].getType().toString());
271             infoMap.put("name", fields[index].getName());
272             Optional<Object> fieldName = getFieldValueByName(fields[index].getName(), obj);
273             if (fieldName.isPresent()) {
274                 infoMap.put("value", fieldName.get());
275             }
276             list.add(infoMap);
277         }
278         return list;
279     }
280 
281     /**
282      * Gets Fields information.
283      *
284      * @param obj Indicates the object.
285      * @param <T> <T>
286      * @return Returns a list of fields.
287      */
getFiledsInfos(T obj)288     public static <T> Map<String, Object> getFiledsInfos(T obj) {
289         if (ProfilerLogManager.isInfoEnabled()) {
290             LOGGER.info("getFiledsInfos");
291         }
292         Field[] fields = obj.getClass().getDeclaredFields();
293         Map infoMap = new HashMap(CommonUtil.collectionSize(LayoutConstants.SIXTEEN));
294         for (int index = 0; index < fields.length; index++) {
295             Optional<Object> fieldName = getFieldValueByName(fields[index].getName(), obj);
296             if (fieldName.isPresent()) {
297                 infoMap.put(fields[index].getName(), fieldName.get());
298             }
299         }
300         return infoMap;
301     }
302 
303     /**
304      * Gets attribute values by attribute name.
305      *
306      * @param obj Indicates the object.
307      * @param <T> <T>
308      * @return Returns a list of attribute names.
309      */
getObjectAttributeNames(T obj)310     public static <T> List<String> getObjectAttributeNames(T obj) {
311         if (ProfilerLogManager.isInfoEnabled()) {
312             LOGGER.info("getObjectAttributeNames");
313         }
314         Field[] fields = obj.getClass().getDeclaredFields();
315         List list = new ArrayList();
316         for (int index = 0; index < fields.length; index++) {
317             list.add(fields[index].getName());
318         }
319         return list;
320     }
321 
322     /**
323      * Get the attribute value by attribute name.
324      *
325      * @param <T> <T>
326      * @param fieldName fieldName
327      * @param object Indicates the object.
328      * @return Object Returns the object value.
329      */
getFieldValueByName(String fieldName, T object)330     private static <T> Optional getFieldValueByName(String fieldName, T object) {
331         if (ProfilerLogManager.isInfoEnabled()) {
332             LOGGER.info("getFieldValueByName");
333         }
334         String firstLetter = fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH);
335         String getter = "get" + firstLetter + fieldName.substring(1);
336         if ("getSerialVersionUID".equals(getter)) {
337             return Optional.empty();
338         }
339         Method method = null;
340         Object value = null;
341         try {
342             method = object.getClass().getMethod(getter, new Class[] {});
343             value = method.invoke(object, new Object[] {});
344         } catch (InvocationTargetException | IllegalAccessException | NoSuchMethodException exception) {
345             if (ProfilerLogManager.isErrorEnabled()) {
346                 LOGGER.error(exception.getMessage());
347             }
348         }
349 
350         return Optional.of(value);
351     }
352 
353     /**
354      * Gets the value of a given object.
355      *
356      * @param object object
357      * @param <T> <T>
358      * @return List <String>
359      */
getObjectValue(T object)360     public static <T> List<String> getObjectValue(T object) {
361         if (ProfilerLogManager.isInfoEnabled()) {
362             LOGGER.info("getObjectValue");
363         }
364         if (object != null && object instanceof Serializable) {
365             Class<?> objectClass = object.getClass();
366             Field[] declaredFields = objectClass.getDeclaredFields();
367             ArrayList<String> list = new ArrayList<>();
368             for (Field field : declaredFields) {
369                 Type type = field.getGenericType();
370                 String colName = field.getName();
371                 if ("class java.lang.String".equals(type.toString())) {
372                     list.add(colName + " varchar(100)");
373                 }
374                 if ("class java.lang.Integer".equals(type.toString()) || "int".equals(type.toString())) {
375                     list.add(colName + " int");
376                 }
377                 if ("class java.lang.Long".equals(type.toString()) || "long".equals(type.toString())) {
378                     list.add(colName + " long");
379                 }
380                 if ("class java.lang.Double".equals(type.toString()) || "double".equals(type.toString())) {
381                     list.add(colName + " double");
382                 }
383                 if ("class java.lang.Boolean".equals(type.toString()) || "boolean".equals(type.toString())) {
384                     list.add(colName + " boolean");
385                 }
386                 if ("class java.util.Date".equals(type.toString())) {
387                     list.add(colName + " date");
388                 }
389             }
390             return list;
391         }
392         return new ArrayList<>();
393     }
394 
395     /**
396      * Get the object name.
397      *
398      * @param object Indicates the object.
399      * @param <T> <T>
400      * @return String
401      */
getObjectName(T object)402     public static <T> String getObjectName(T object) {
403         if (ProfilerLogManager.isInfoEnabled()) {
404             LOGGER.info("getObjectName");
405         }
406         if (object != null) {
407             return object.getClass().getSimpleName();
408         }
409         return "";
410     }
411 }
412