Code Smells in jujuvnfmadapter utils
[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
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) {
245                                     delFiles(newPath);
246                             }
247                             if (new File(newPath).exists() && flag) {
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                     } else {
259                             throw new FileNotFoundException("the " + oldfile + " is not exits ");
260                     }
261
262             }
263
264     /**
265      * @param filePathAndName
266      *            String exp c:/fqf.txt
267      * @param fileContent
268      *            String
269      * @return boolean
270      */
271     public static boolean delFiles(String filePathAndName) {
272
273         boolean flag = false;
274         File myDelFile = new File(filePathAndName);
275         if (!myDelFile.exists())
276             return true;
277         if (myDelFile.isDirectory()) {
278             File[] fs = myDelFile.listFiles();
279             for (int i = 0; i < fs.length; i++) {//no need to assign
280                 if (fs[i].isFile())
281                     fs[i].delete();
282                 if (fs[i].isDirectory()) {
283                     delFiles(fs[i].getAbsolutePath());
284                     fs[i].delete();
285                 }
286             }
287         }
288         flag = myDelFile.delete();
289         return flag;
290     }
291
292     /**
293      * create new file
294      * 
295      * @param filePathAndName
296      *            String
297      * @return
298      * @throws IOException
299      */
300     public static File newFile(String fileName) throws IOException {
301         File file = new File(fileName);
302
303         newFloder(file.getParentFile().toString());
304
305         if (!file.exists()) {
306             file.createNewFile();
307         }
308         return file;
309     }
310
311     /**
312      * the file down all the hidden files
313      * 
314      * @author sunny.sun
315      * */
316     public static List<File> getFiles(String path) {
317
318         List<File> list = new ArrayList<>();
319         File file = new File(path);
320         if (!file.exists()) {
321
322             file.mkdirs();
323         }
324
325         File[] files = file.listFiles();
326         for (int i = 0; i < files.length; i++) {
327             if (files[i].isFile() && !files[i].isHidden()) {
328                 list.add(files[i]);
329             }
330             if (files[i].isDirectory() && !files[i].isHidden()) {
331                 List<File> list2 = getFiles(files[i].getPath());// use myself
332                 list.addAll(list2);
333             }
334         }
335         return list;
336     }
337
338     /**
339      * causes the os of this computer is Windows
340      * 
341      * @author sunny.sun
342      * */
343     public static boolean isWindows() {
344
345         String os = System.getProperty("os.name").toLowerCase();
346         // windows
347         return (os.indexOf("win") >= 0);
348
349     }
350
351     public static void copy(String oldfile, String newfile, boolean flag)
352             throws IOException {
353         File oldf = new File(oldfile);
354         File newf = new File(newfile);
355         boolean oisd = (oldfile.endsWith("/") || oldfile.endsWith("\\"));
356         boolean nisd = (newfile.endsWith("/") || newfile.endsWith("\\"));
357
358         if (!oldf.exists()) {
359                  throw new FileNotFoundException("the  from data is not exists");
360         }
361         if (oldf.exists() && !newf.exists()) {
362             if (newfile.endsWith("/") || newfile.endsWith("\\")) {
363                 newFloder(newfile);
364             } else {
365                 newFile(newfile);
366             }
367         }
368         if (oldf.exists() && oisd && !nisd) {
369                  throw new FileNotFoundException("the  from data is directory,but the to data is a file");
370         }
371         if (!oisd && !nisd) {
372             copyFile(oldf.getAbsolutePath(), newf.getAbsolutePath(), flag);
373         }
374         if (oisd && nisd) {
375             newFloder(newf.getAbsolutePath());
376             List<File> list = getFiles(oldf.getAbsolutePath());
377             for (int i = 0; i < list.size(); i++) {
378                 copyFile(list.get(i).getAbsolutePath(), newf.getAbsolutePath()
379                         + "/" + list.get(i).getName(), flag);
380             }
381         }
382         if (!oisd && nisd) {
383             newFloder(newf.getAbsolutePath());
384             copyFile(oldf.getAbsolutePath(), newf.getAbsolutePath() + "/"
385                     + oldf.getName(), flag);
386         }
387
388     }
389
390     /**
391      * causes the os of this computer is mac
392      * 
393      * @author sunny.sun
394      * */
395     public static boolean isMac() {
396
397         String os = System.getProperty("os.name").toLowerCase();
398         // Mac
399         return (os.indexOf("mac") >= 0);
400
401     }
402
403     /**
404      * causes the os of this computer is unix
405      * 
406      * @author sunny.sun
407      * */
408     public static boolean isUnix() {
409
410         String os = System.getProperty("os.name").toLowerCase();
411         // linux or unix
412         return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0);
413
414     }
415
416     /**
417      * @param file
418      * @return
419      * @throws Exception
420      */
421     public static boolean isUsed(String file) throws IOException {
422         File f = new File(file);
423         if (!f.exists()) {
424             throw new FileNotFoundException("the file is not exists ..");
425         }
426         File f1 = new File(file + ".temp");
427         f.renameTo(f1);
428         if (f.exists()) {
429             return true;
430         } else {
431             f1.renameTo(f);
432             return false;
433         }
434
435     }
436     /**
437      * Remove the file name's extension (only remove the last) 
438      * <br/>
439      * 
440      * @param file
441      * @return
442      * @since  NFVO 0.5
443      */
444     public static String getBaseFileName(File file){
445         if(file.getName().lastIndexOf(".") > 0){
446             return file.getName().substring(0,file.getName().lastIndexOf("."));
447         }else{
448             return file.getName();
449         }
450        
451     }
452     
453     /**
454      * fix file path to linux seperate,and remove the head and end slash
455      * <br/>
456      * 
457      * @param path
458      * @return
459      * @since  NFVO 0.5
460      */
461     public static String fixPath(String path){
462         String newPath = path;
463         if(path == null){
464             return newPath;
465         }
466         newPath = newPath.replaceAll("\\\\", "/");
467         if(newPath.startsWith("/")){
468             newPath = newPath.substring(1, newPath.length()); 
469         }
470         if(newPath.endsWith("/")){
471             newPath = newPath.substring(0, newPath.length()-1); 
472         }
473         return newPath;
474     }
475     
476     /**
477      * fix file path to linux seperate,and add the head and end slash
478      * <br/>
479      * 
480      * @param path
481      * @return
482      * @since  NFVO 0.5
483      */
484     public static String getFriendlyPath(String path){
485         String newPath = path;
486         if(path == null){
487             return newPath;
488         }
489         newPath = newPath.replaceAll("\\\\", "/");
490         if(!newPath.startsWith("/")){
491             newPath = "/"+newPath;
492         }
493         if(!newPath.endsWith("/")){
494             newPath = newPath + "/";
495         }
496         return newPath;
497     }
498 }