summaryrefslogtreecommitdiffstats
path: root/juju/juju-vnfmadapter/Juju-vnfmadapterService/service/src/main/java/org/onap/vfc/nfvo/vnfm/gvnfm/jujuvnfmadapter/common/UnCompressUtil.java
blob: f2098fc45be9b5fb30f5867db6f143f922d41f04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/**
 * Copyright (c) 2016, Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.compress.compressors.xz.XZCompressorInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <br/>
 * <p>
 * </p>
 * 
 * @author quanzhong@huawei.com
 * @version NFVO 0.5 Oct 28, 2016
 */
public class UnCompressUtil {

    private static Logger log = LoggerFactory.getLogger(UnCompressUtil.class);

    private static Map<String, String> archiveMap = new HashMap<>();

    private static Map<String, String> compressorMap = new HashMap<>();

    static {
        // archive type
        archiveMap.put(ArchiveStreamFactory.AR, ArchiveStreamFactory.AR);
        archiveMap.put(ArchiveStreamFactory.ARJ, ArchiveStreamFactory.ARJ);
        archiveMap.put(ArchiveStreamFactory.CPIO, ArchiveStreamFactory.CPIO);
        archiveMap.put(ArchiveStreamFactory.DUMP, ArchiveStreamFactory.DUMP);
        archiveMap.put(ArchiveStreamFactory.JAR, ArchiveStreamFactory.JAR);
        archiveMap.put(ArchiveStreamFactory.SEVEN_Z, ArchiveStreamFactory.SEVEN_Z);
        archiveMap.put(ArchiveStreamFactory.TAR, ArchiveStreamFactory.TAR);
        archiveMap.put(ArchiveStreamFactory.ZIP, ArchiveStreamFactory.ZIP);

        // compressor type
        compressorMap.put(CompressorStreamFactory.BZIP2, CompressorStreamFactory.BZIP2);
        compressorMap.put(CompressorStreamFactory.DEFLATE, CompressorStreamFactory.DEFLATE);
        compressorMap.put(CompressorStreamFactory.GZIP, CompressorStreamFactory.GZIP);
        compressorMap.put(CompressorStreamFactory.LZMA, CompressorStreamFactory.LZMA);
        compressorMap.put(CompressorStreamFactory.PACK200, CompressorStreamFactory.PACK200);
        compressorMap.put(CompressorStreamFactory.SNAPPY_FRAMED, CompressorStreamFactory.SNAPPY_FRAMED);
        compressorMap.put(CompressorStreamFactory.SNAPPY_RAW, CompressorStreamFactory.SNAPPY_RAW);
        compressorMap.put(CompressorStreamFactory.XZ, CompressorStreamFactory.XZ);
        compressorMap.put(CompressorStreamFactory.Z, CompressorStreamFactory.Z);
    }

    /**
     * tar.gz
     * <br/>
     * 
     * @param zipfileName
     * @param outputDirectory
     * @param fileNames
     * @return
     * @since NFVO 0.5
     */
    public static boolean unCompressGzip(String zipfileName, String outputDirectory, List<String> fileNames) {
        try (
            FileInputStream fis = new FileInputStream(zipfileName);
            GZIPInputStream gis = new GZIPInputStream(new BufferedInputStream(fis));
            ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", gis);
            BufferedInputStream bis = new BufferedInputStream(in)){
            TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry();
            while(entry != null) {
                String name = entry.getName();
                String[] names = name.split("/");
                String fileName = outputDirectory;
                for(int i = 0; i < names.length; i++) {
                    String str = names[i];
                    fileName = fileName + File.separator + str;
                }
                if(name.endsWith("/")) {
                    FileUtils.mkDirs(fileName);
		} else {
			File file = getRealFileName(outputDirectory, name);
			if(null != fileNames) {
				fileNames.add(file.getName());
			}
			try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))){
				int b = -1;
				while((b = bis.read()) != -1) {
					bos.write(b);
				}
				log.debug("ungzip to:" + file.getCanonicalPath());
			}
		}
                entry = (TarArchiveEntry)in.getNextEntry();
            }
            return true;
        } catch(Exception e) {
            log.error("UnCompressGZip faield:", e);
            return false;
        } 
    }

    public static void unCompressAllZip(String sourcePath, String targetPath) throws FileNotFoundException {
        for(File file : FileUtils.listFiles(new File(sourcePath))) {
            unCompressZip(file.getAbsolutePath(),
                    targetPath + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")),new ArrayList<String>());
        }
    }

    /**
     * zip
     * <br/>
     * 
     * @param sourceFile unzipPath
     * @param targetPath zippath
     * @param fileNames
     * @since NFVO 0.5
     */
    public static boolean unCompressZip(String sourceFile, String targetPath,List<String> fileNames) {
        try (
            FileInputStream fis = new FileInputStream(sourceFile);
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis))){
            ZipEntry entry = null;
            while((entry = zis.getNextEntry()) != null) {
                String name = entry.getName();
                String[] names = name.split("/");
                String fileName = targetPath;
                for(int i = 0; i < names.length; i++) {
                    String str = names[i];
                    fileName = fileName + File.separator + str;
                }
                if(name.endsWith("/")) {
                    FileUtils.mkDirs(fileName);
                } else {
                    int count;
                    byte[] data = new byte[2048];
                    File file = getRealFileName(targetPath, name);
                    fileNames.add(file.getName());

                    try(BufferedOutputStream dest = new BufferedOutputStream(new FileOutputStream(file))){

                    while((count = zis.read(data, 0, 2048)) != -1) {
                        dest.write(data, 0, count);
                    }
                    log.debug("unzip to:" + file.getCanonicalPath());}
                }
            }
            zis.close();
            return true;
        } catch(Exception e) {
            log.error("UnCompressZip faield:", e);
        }
        return false;
    }

    private static File getRealFileName(String zippath, String absFileName) {
        String[] dirs = absFileName.split("/", absFileName.length());

        File ret = new File(zippath);

        if(dirs.length > 1) {
            for(int i = 0; i < dirs.length - 1; i++) {
                ret = new File(ret, dirs[i]);
            }
        }

        if(!ret.exists()) {
            ret.mkdirs();
        }

        ret = new File(ret, dirs[dirs.length - 1]);

        return ret;
    }

    /**
     * tar.xz
     * <br/>
     * 
     * @param zipfileName
     * @param outputDirectory
     * @param fileNames
     * @return
     * @since NFVO 0.5
     */
    public static boolean unCompressTarXZ(String zipfileName, String outputDirectory, List<String> fileNames) {
        try( 
            XZCompressorInputStream xzis =
                    new XZCompressorInputStream(new BufferedInputStream(new FileInputStream(zipfileName)));
            ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("tar", xzis);
            BufferedInputStream bis = new BufferedInputStream(in)){
            TarArchiveEntry entry = (TarArchiveEntry)in.getNextEntry();
            while(entry != null) {
                String name = entry.getName();
                String[] names = name.split("/");
                String fileName = outputDirectory;
                for(int i = 0; i < names.length; i++) {
                    String str = names[i];
                    fileName = fileName + File.separator + str;
                }
                if(name.endsWith("/")) {
                    FileUtils.mkDirs(fileName);
                } else {
                    File file = getRealFileName(outputDirectory, name);
                    if(null != fileNames) {
                        fileNames.add(file.getName());
                    }
                    try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))){
                    int b = -1;
                    while((b = bis.read()) != -1) {
                        bos.write(b);
                    }
                    log.debug("ungzip to:" + file.getCanonicalPath());}
                }
                entry = (TarArchiveEntry)in.getNextEntry();
            }
            return true;
        } catch(Exception e) {
            log.error("unCompressTarXZ faield:", e);
        } 
        return false;
    }
    
    /**
     * only support .zip/.tar.gz/.tar.xz
     * <br/>
     * 
     * @param zipfileName
     * @param outputDirectory
     * @param fileNames
     * @return
     * @since  NFVO 0.5
     */
    public static boolean unCompress(String zipfileName, String outputDirectory, List<String> fileNames) {
        if(zipfileName.endsWith(".zip")){
            return unCompressZip(zipfileName,outputDirectory,fileNames);
        }else if(zipfileName.endsWith(".tar.gz")){
            return unCompressGzip(zipfileName,outputDirectory,fileNames);
        }else if(zipfileName.endsWith(".tar.xz")){
            return unCompressTarXZ(zipfileName,outputDirectory,fileNames);
        }else{
            log.error("not supprot file type:->"+zipfileName);
            return false;
        }
    }

        
}