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