• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 com.update.check.utils;
17 
18 import com.alibaba.fastjson.JSON;
19 import com.alibaba.fastjson.JSONArray;
20 import com.alibaba.fastjson.JSONObject;
21 import com.update.check.log.Logger;
22 import com.update.check.dto.ApiDiffResultDto;
23 import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
24 import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
25 import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
26 import org.apache.commons.compress.utils.IOUtils;
27 
28 import java.io.File;
29 import java.io.InputStream;
30 import java.io.IOException;
31 import java.io.FileOutputStream;
32 import java.io.FileReader;
33 import java.io.OutputStreamWriter;
34 import java.io.FileInputStream;
35 import java.io.InputStreamReader;
36 import java.io.BufferedWriter;
37 import java.io.Reader;
38 import java.nio.charset.StandardCharsets;
39 import java.nio.file.Files;
40 import java.util.List;
41 import java.util.Properties;
42 
43 /**
44  * FileUtils
45  *
46  * @since 23-04-07
47  */
48 public class FileUtils {
49     private static final String LOG_TAG = FileUtils.class.getName();
50     private static final Logger LOGGER = Logger.createLogger();
51 
52     /**
53      * getApiTools
54      *
55      * @since 23-04-07
56      */
getApiTools()57     public void getApiTools() {
58         try {
59 
60             // getLastDir
61             String lastDir = getLastDir();
62             File updateCheck = new File(lastDir, "updateCheck");
63             if (!updateCheck.exists()) {
64                 updateCheck.mkdirs();
65             }
66 
67             // api diff tool
68             File diffPath = new File(updateCheck.toString(), "api-diff");
69             if (!diffPath.exists()) {
70                 InputStream apiDiffInputStream = this.getToolsInputStream("api-diff.tar.gz");
71                 if (apiDiffInputStream != null) {
72                     unGzipFile(apiDiffInputStream, updateCheck);
73                 }
74             }
75 
76             // application api scanning tool
77             File applicationPath = new File(updateCheck.toString(), "collect_application_api");
78             if (!applicationPath.exists()) {
79                 InputStream applicationInputStream = this.getToolsInputStream("collect_application_api.tar.gz");
80                 if (applicationInputStream != null) {
81                     unGzipFile(applicationInputStream, updateCheck);
82                 }
83             }
84         } catch (IOException e) {
85             LOGGER.error(LOG_TAG, "get api tools error! " + e.getMessage());
86         }
87 
88     }
89 
90     /**
91      * getLastDir
92      *
93      * @return last dir
94      */
getLastDir()95     public static String getLastDir() {
96         return File.listRoots()[File.listRoots().length - 1].toString();
97     }
98 
getToolsInputStream(String toolName)99     private InputStream getToolsInputStream(String toolName) {
100         return getClass().getClassLoader().getResourceAsStream(toolName);
101     }
102 
103     /**
104      * unGzipFile
105      *
106      * @param inputStream inputStream
107      * @param targetDir   targetDir
108      * @throws IOException If an I/O error occurs
109      */
unGzipFile(InputStream inputStream, File targetDir)110     public static void unGzipFile(InputStream inputStream, File targetDir)
111             throws IOException {
112         TarArchiveInputStream tarArchiveInputStream =
113                 new TarArchiveInputStream(
114                         new GzipCompressorInputStream(inputStream));
115         TarArchiveEntry entry;
116         while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) {
117             if (entry.isDirectory()) {
118                 continue;
119             }
120             File targetFile = new File(targetDir, entry.getName());
121             File parent = targetFile.getParentFile();
122             if (!parent.exists()) {
123                 parent.mkdirs();
124             }
125             IOUtils.copy(tarArchiveInputStream, Files.newOutputStream(targetFile.toPath()));
126         }
127     }
128 
129     /**
130      * getApplicationApiType
131      *
132      * @param projectBasePath projectBasePath
133      * @return api type
134      */
getApplicationApiType(String projectBasePath)135     public static String getApplicationApiType(String projectBasePath) {
136         File buildFile = new File(projectBasePath, "build-profile.json5");
137         try {
138             String jsonString = getJsonString(buildFile);
139             Object childParse = JSONObject.parse(jsonString);
140             JSONObject parse = null;
141             if (childParse instanceof JSONObject) {
142                 parse = (JSONObject) childParse;
143             }
144             Object childModel = parse.get("modules");
145             JSONArray modules = null;
146             if (childModel instanceof JSONArray) {
147                 modules = (JSONArray) childModel;
148             }
149             Object childObject = modules.get(0);
150             JSONObject model = null;
151             if (childObject instanceof JSONObject) {
152                 model = (JSONObject) childObject;
153             }
154             String modelName = String.valueOf(model.get("name"));
155             File file = new File(projectBasePath, modelName + "\\build-profile.json5");
156             String modelJson = getJsonString(file);
157             Object child = JSONObject.parse(modelJson);
158             JSONObject parseModel = null;
159             if (child instanceof JSONObject) {
160                 parseModel = (JSONObject) child;
161             }
162             String result = null;
163             Object objectResult = parseModel.get("apiType");
164             if (objectResult instanceof String) {
165                 result = (String) objectResult;
166             }
167             return result;
168         } catch (IOException e) {
169             LOGGER.error(LOG_TAG, e.getMessage());
170             return null;
171         }
172     }
173 
174     /**
175      * getSdkVersionFromJsonFile
176      *
177      * @param jsonFilePath jsonFilePath
178      * @return sdk version
179      * @throws IOException If an I/O error occurs
180      */
getSdkVersionFromJsonFile(String jsonFilePath)181     public static String getSdkVersionFromJsonFile(String jsonFilePath) {
182         try {
183             File jsonFile = new File(jsonFilePath);
184             String jsonStr = getJsonString(jsonFile);
185             ApiDiffResultDto dto = JSON.parseObject(jsonStr, ApiDiffResultDto.class);
186             return dto.getVersion();
187         } catch (IOException e) {
188             LOGGER.error(LOG_TAG, e.getMessage());
189             return "";
190         }
191     }
192 
193     /**
194      * readJsonFileToJavaList
195      *
196      * @param jsonFilePath jsonFilePath
197      * @param clazz        clazz
198      * @param <T>          T
199      * @return class
200      * @throws IOException If an I/O error occurs
201      */
readJsonFileToJavaList(String jsonFilePath, Class<T> clazz)202     public static <T> List<T> readJsonFileToJavaList(String jsonFilePath, Class<T> clazz) throws IOException {
203         File jsonFile = new File(jsonFilePath);
204         String jsonStr = getJsonString(jsonFile);
205         return JSON.parseArray(jsonStr, clazz);
206     }
207 
208     /**
209      * writerJsonToFile
210      *
211      * @param jsonString   jsonString
212      * @param jsonFilePath jsonFilePath
213      */
writerJsonToFile(String jsonString, String jsonFilePath)214     public static void writerJsonToFile(String jsonString, String jsonFilePath) {
215         BufferedWriter bufferedWriter = null;
216         try {
217             File file = new File(jsonFilePath);
218             if (!file.getParentFile().exists()) {
219                 file.getParentFile().mkdirs();
220                 file.createNewFile();
221             }
222             bufferedWriter = new BufferedWriter(
223                     new OutputStreamWriter(
224                             new FileOutputStream(file), StandardCharsets.UTF_8
225                     ));
226             bufferedWriter.write(jsonString);
227         } catch (IOException e) {
228             LOGGER.error(LOG_TAG, e.getMessage());
229         } finally {
230             if (null != bufferedWriter) {
231                 try {
232                     bufferedWriter.close();
233                 } catch (IOException exception) {
234                     exception.printStackTrace();
235                 }
236             }
237         }
238     }
239 
240     /**
241      * getNodePath
242      *
243      * @param projectPath projectPath
244      * @param file        file
245      * @param name        name
246      * @return node path
247      */
getNodePath(String projectPath, String file, String name)248     public static String getNodePath(String projectPath, String file, String name) {
249         Properties properties = new Properties();
250         File props = new File(projectPath, file);
251         if (!props.exists()) {
252             return null;
253         }
254         try (InputStream in = new FileInputStream(props)) {
255             properties.load(in);
256             return properties.getProperty(name);
257         } catch (IOException e) {
258             LOGGER.error(LOG_TAG, e.getMessage());
259             return null;
260         }
261     }
262 
263     /**
264      * getCompileSdkVersion
265      *
266      * @param projectPath projectPath
267      * @return sdk version
268      * @throws IOException If an I/O error occurs
269      */
getCompileSdkVersion(String projectPath)270     public static String getCompileSdkVersion(String projectPath) throws IOException {
271         if (projectPath == null) {
272             return null;
273         }
274         File buildFile = new File(projectPath, "build-profile.json5");
275 
276         if (!buildFile.exists()) {
277             return null;
278         }
279         return getCompileSdkVersion(buildFile);
280     }
281 
282     /**
283      * getCompileSdkVersion
284      *
285      * @param buildFile buildFile
286      * @return sdk version
287      * @throws IOException If an I/O error occurs
288      */
getCompileSdkVersion(File buildFile)289     public static String getCompileSdkVersion(File buildFile) throws IOException {
290         String jsonString = getJsonString(buildFile);
291         Object childParse = JSONObject.parse(jsonString);
292         JSONObject parse = null;
293         if (childParse instanceof JSONObject) {
294             parse = (JSONObject) childParse;
295         }
296         Object parseApp = parse.get("app");
297         JSONObject appJson = null;
298         if (parseApp instanceof JSONObject) {
299             appJson = (JSONObject) parseApp;
300         }
301         if (appJson.get("compileSdkVersion") != null) {
302             return String.valueOf(appJson.get("compileSdkVersion"));
303         }
304         Object products = appJson.get("products");
305         JSONArray modules = null;
306         if (products instanceof JSONArray) {
307             modules = (JSONArray) products;
308         }
309         Object childObject = modules.get(0);
310         JSONObject product = null;
311         if (childObject instanceof JSONObject) {
312             product = (JSONObject) childObject;
313         }
314         return String.valueOf(product.get("compileSdkVersion"));
315     }
316 
317     /**
318      * getJsonString
319      *
320      * @param buildFile buildFile
321      * @return json string
322      * @throws IOException If an I/O error occurs
323      */
getJsonString(File buildFile)324     public static String getJsonString(File buildFile) throws IOException {
325         FileReader fileReader = new FileReader(buildFile);
326         Reader reader = new InputStreamReader(new FileInputStream(buildFile), StandardCharsets.UTF_8);
327         int ch = 0;
328         StringBuilder stringBuilder = new StringBuilder();
329         while ((ch = reader.read()) != -1) {
330             stringBuilder.append((char) ch);
331         }
332         fileReader.close();
333         reader.close();
334         return stringBuilder.toString();
335     }
336 
337 }