357f2c545bc40a3b9e8572e524d4dc38b9ebf432
[vfc/nfvo/driver/vnfm/gvnfm.git] /
1 /*
2  * Copyright (c) 2016, Huawei Technologies Co., Ltd.
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
17 package org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.common;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.FileNotFoundException;
22 import java.io.FileOutputStream;
23 import java.io.FileReader;
24 import java.io.IOException;
25 import java.io.OutputStream;
26 import java.util.ArrayList;
27 import java.util.List;
28
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33  * FileUtils
34  * <br/>
35  * <p>
36  * </p>
37  * 
38  * @author quanzhong@huawei.com
39  * @version NFVO 0.5 Sep 23, 2016
40  */
41 public class FileUtils {
42
43     public static final String UTF8 = "UTF-8";
44
45     public static final String GBK = "GBK";
46
47     private static Logger log = LoggerFactory.getLogger(FileUtils.class);
48
49     private FileUtils(){
50         
51     }
52     /**
53      * get current classPath as str. and the trailing slash will be remove
54      * <br/>
55      * 
56      * @return
57      * @since  NFVO 0.5
58      */
59     public static String getClassPath(){
60         String path = ClassLoader.getSystemClassLoader().getResource("./").getPath();
61         if(path.endsWith("/")){
62             path = path.substring(0, path.length()-1);
63         }
64         return path;
65     }
66     /**
67      * read data from the file
68      * <br/>
69      * 
70      * @param file
71      * @param charsetName
72      * @return
73      * @throws IOException
74      * @since  NFVO 0.5
75      */
76     public static byte[] readFile(File file, String charsetName) throws IOException {
77             if(file != null) {
78
79                     try( FileReader reader = new FileReader(file)){
80                             StringBuilder buffer = new StringBuilder();
81                             char[] cbuf = new char[1024];
82                             int legth;
83                             while((legth = reader.read(cbuf)) != -1) {
84                                     buffer.append(new String(cbuf, 0, legth));
85                             }
86                             reader.close();
87                             return buffer.toString().getBytes(charsetName);
88                     }catch(IOException e){
89                         log.error("read file", e);
90                         throw e;
91                 }
92             }
93             return new byte[]{};
94     }
95
96     /**
97      * write data as file to the filePath
98      * <br/>
99      * 
100      * @param data
101      * @param filePath
102      * @return
103      * @since  NFVO 0.5
104      */
105     public static int writeFile(byte[] data, String filePath) {
106         try( 
107             OutputStream out = new FileOutputStream(filePath)){
108             out.write(data, 0, data.length);
109             out.close();
110             return 0;
111         } catch (Exception e) {
112             log.error("write file fail,filePath:"+filePath, e);
113         }
114         return -1;
115     }
116     
117     /**
118      * List all files in directory
119      * @param file
120      * @return
121      * @throws FileNotFoundException 
122      */
123     public static  List<File> listFiles(File file) throws FileNotFoundException{
124         List<File> list = new ArrayList<>();
125         list(file, list);
126         return list;
127     }
128     /**
129      * List all files in directory
130      * @param file
131      * @param list
132      * @throws FileNotFoundException 
133      */
134     private static void list(File file, List<File> list) throws FileNotFoundException{
135         if(!file.exists()){
136             throw new FileNotFoundException(file.getAbsolutePath());
137         }
138         File[] files = file.listFiles();
139         if(files != null && files.length >  0 ){
140             for(File f : files){
141                 if(f.isFile()){
142                     list.add(f);
143                 }else{
144                     list(f, list);
145                 }
146             }
147         }
148     }
149     
150     
151     /**
152      * createDirs (cycle create)
153      * <br/>
154      * 
155      * @param file
156      * @since  NFVO 0.5
157      */
158     public static void createDirs(File file){
159         if(file.getParentFile().exists()){
160             file.mkdir();
161         }else{
162             createDirs(file.getParentFile());
163             file.mkdir();
164         }
165     }
166     
167     /**
168      *mkDirs 
169      * <br/>
170      * 
171      * @param path
172      * @since  NFVO 0.5
173      */
174     public static void mkDirs(String path){
175         File file = new File(path);
176         createDirs(file);
177     }
178     
179     
180     
181     public static String getSuperUrl(String file) {
182         return new File(file).getParentFile().getAbsolutePath();
183
184     }
185
186     /**
187      * absolute url
188      * 
189      * @author sunny.sun
190      * @return file this application absolute url
191      */
192     public static String getAppAbsoluteUrl() {
193
194         // ��ȡ��class���ڵľ���·��
195         String file = UnCompressUtil.class.getClassLoader().getResource("/") == null ? null
196                 : UnCompressUtil.class.getClassLoader().getResource("/").toString();
197         if (file == null) {
198             file = UnCompressUtil.class.getProtectionDomain().getCodeSource()
199                     .getLocation().getFile().substring(1);
200         }
201         // ��class�ļ���war��ʱ������"zip:D:/ ..."����·��
202         if (file.startsWith("zip")) {
203             file = file.substring(4);
204
205             // ��class�ļ���class�ļ���ʱ������"file:/F:/ ..."����·��
206         } else if (file.startsWith("file")) {
207             file = file.substring(6);
208
209             // ��class�ļ���jar�ļ���ʱ������"jar:file:/F:/ ..."����·��
210         } else if (file.startsWith("jar")) {
211             file = file.substring(10);
212         }
213
214         if (!isWindows())
215             return ("/" + file).replace("%20", " ");
216
217         return file.replace("%20", " ");
218     }
219
220     public static String getWEBClassAbsoluteUrl() {
221
222         return getAppAbsoluteUrl();
223     }
224
225     /**
226      * @param floder
227      * @return
228      */
229     public static File newFloder(String floder) {
230         File file = new File(floder);
231         if (!file.exists()) {
232             file.mkdirs();
233         }
234         return file;
235     }
236
237
238
239     public static void copyFile(String oldPath, String newPath, boolean flag)
240             throws IOException {
241                     int byteread = 0;
242                     File oldfile = new File(oldPath);
243                     if (oldfile.exists()) {
244                             if (flag == false) {
245                                     delFiles(newPath);
246                             }
247                             if (new File(newPath).exists() && flag == true) {
248                                     return;
249                             }
250                             newFile(newPath);
251                             try(FileInputStream fis = new FileInputStream(oldPath);
252                                             FileOutputStream fos = new FileOutputStream(newPath)){
253                                     byte[] buffer = new byte[1024];
254                                     while ((byteread = fis.read(buffer)) != -1) {
255                                             fos.write(buffer, 0, byteread);
256                                     }
257                             }
258                             //fos.close();
259                             //fis.close();
260                     } else {
261                             throw new FileNotFoundException("the " + oldfile + " is not exits ");
262                     }
263
264             }
265
266     /**
267      * @param filePathAndName
268      *            String exp c:/fqf.txt
269      * @param fileContent
270      *            String
271      * @return boolean
272      */
273     public static boolean delFiles(String filePathAndName) {
274
275         boolean flag = false;
276         File myDelFile = new File(filePathAndName);
277         if (!myDelFile.exists())
278             return true;
279         if (myDelFile.isDirectory()) {
280             File[] fs = myDelFile.listFiles();
281             for (int i = 0; i < fs.length; i++) {
282                 if (fs[i].isFile())
283                     flag = fs[i].delete();
284                 if (fs[i].isDirectory()) {
285                     flag = delFiles(fs[i].getAbsolutePath());
286                     flag = fs[i].delete();
287                 }
288             }
289         }
290         flag = myDelFile.delete();
291         return flag;
292     }
293
294     /**
295      * create new file
296      * 
297      * @param filePathAndName
298      *            String
299      * @return
300      * @throws IOException
301      */
302     public static File newFile(String fileName) throws IOException {
303         File file = new File(fileName);
304
305         newFloder(file.getParentFile().toString());
306
307         if (!file.exists()) {
308             file.createNewFile();
309         }
310         return file;
311     }
312
313     /**
314      * the file down all the hidden files
315      * 
316      * @author sunny.sun
317      * */
318     public static List<File> getFiles(String path) {
319
320         List<File> list = new ArrayList<File>();
321         File file = new File(path);
322         if (!file.exists()) {
323
324             file.mkdirs();
325         }
326
327         File[] files = file.listFiles();
328         for (int i = 0; i < files.length; i++) {
329             if (files[i].isFile() && !files[i].isHidden()) {
330                 list.add(files[i]);
331             }
332             if (files[i].isDirectory() && !files[i].isHidden()) {
333                 List<File> list2 = getFiles(files[i].getPath());// use myself
334                 list.addAll(list2);
335             }
336         }
337         return list;
338     }
339
340     /**
341      * causes the os of this computer is Windows
342      * 
343      * @author sunny.sun
344      * */
345     public static boolean isWindows() {
346
347         String os = System.getProperty("os.name").toLowerCase();
348         // windows
349         return (os.indexOf("win") >= 0);
350
351     }
352
353     public static void copy(String oldfile, String newfile, boolean flag)
354             throws IOException {
355         File oldf = new File(oldfile);
356         File newf = new File(newfile);
357         boolean oisd = (oldfile.endsWith("/") || oldfile.endsWith("\\"));
358         boolean nisd = (newfile.endsWith("/") || newfile.endsWith("\\"));
359
360         if (!oldf.exists()) {
361                  throw new FileNotFoundException("the  from data is not exists");
362         }
363         if (oldf.exists() && !newf.exists()) {
364             if (newfile.endsWith("/") || newfile.endsWith("\\")) {
365                 newFloder(newfile);
366             } else {
367                 newFile(newfile);
368             }
369         }
370         if (oldf.exists() && oisd && !nisd) {
371                  throw new FileNotFoundException("the  from data is directory,but the to data is a file");
372         }
373         if (!oisd && !nisd) {
374             copyFile(oldf.getAbsolutePath(), newf.getAbsolutePath(), flag);
375         }
376         if (oisd && nisd) {
377             newFloder(newf.getAbsolutePath());
378             List<File> list = getFiles(oldf.getAbsolutePath());
379             for (int i = 0; i < list.size(); i++) {
380                 copyFile(list.get(i).getAbsolutePath(), newf.getAbsolutePath()
381                         + "/" + list.get(i).getName(), flag);
382             }
383         }
384         if (!oisd && nisd) {
385             newFloder(newf.getAbsolutePath());
386             copyFile(oldf.getAbsolutePath(), newf.getAbsolutePath() + "/"
387                     + oldf.getName(), flag);
388         }
389
390     }
391
392     /**
393      * causes the os of this computer is mac
394      * 
395      * @author sunny.sun
396      * */
397     public static boolean isMac() {
398
399         String os = System.getProperty("os.name").toLowerCase();
400         // Mac
401         return (os.indexOf("mac") >= 0);
402
403     }
404
405     /**
406      * causes the os of this computer is unix
407      * 
408      * @author sunny.sun
409      * */
410     public static boolean isUnix() {
411
412         String os = System.getProperty("os.name").toLowerCase();
413         // linux or unix
414         return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0);
415
416     }
417
418     /**
419      * @param file
420      * @return
421      * @throws Exception
422      */
423     public static boolean isUsed(String file) throws IOException {
424         File f = new File(file);
425         if (!f.exists()) {
426             throw new FileNotFoundException("the file is not exists ..");
427         }
428         File f1 = new File(file + ".temp");
429         f.renameTo(f1);
430         if (f.exists()) {
431             return true;
432         } else {
433             f1.renameTo(f);
434             return false;
435         }
436
437     }
438     /**
439      * Remove the file name's extension (only remove the last) 
440      * <br/>
441      * 
442      * @param file
443      * @return
444      * @since  NFVO 0.5
445      */
446     public static String getBaseFileName(File file){
447         if(file.getName().lastIndexOf(".") > 0){
448             return file.getName().substring(0,file.getName().lastIndexOf("."));
449         }else{
450             return file.getName();
451         }
452        
453     }
454     
455     /**
456      * fix file path to linux seperate,and remove the head and end slash
457      * <br/>
458      * 
459      * @param path
460      * @return
461      * @since  NFVO 0.5
462      */
463     public static String fixPath(String path){
464         String newPath = path;
465         if(path == null){
466             return newPath;
467         }
468         newPath = newPath.replaceAll("\\\\", "/");
469         if(newPath.startsWith("/")){
470             newPath = newPath.substring(1, newPath.length()); 
471         }
472         if(newPath.endsWith("/")){
473             newPath = newPath.substring(0, newPath.length()-1); 
474         }
475         return newPath;
476     }
477     
478     /**
479      * fix file path to linux seperate,and add the head and end slash
480      * <br/>
481      * 
482      * @param path
483      * @return
484      * @since  NFVO 0.5
485      */
486     public static String getFriendlyPath(String path){
487         String newPath = path;
488         if(path == null){
489             return newPath;
490         }
491         newPath = newPath.replaceAll("\\\\", "/");
492         if(!newPath.startsWith("/")){
493             newPath = "/"+newPath;
494         }
495         if(!newPath.endsWith("/")){
496             newPath = newPath + "/";
497         }
498         return newPath;
499     }
500 }