1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package io.wcm.maven.plugins.nodejs.installation;
21
22 import java.io.BufferedOutputStream;
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29
30 import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
31 import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
32 import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
33 import org.apache.commons.io.IOUtils;
34 import org.apache.maven.plugin.MojoExecutionException;
35
36
37
38
39 public class TarUnArchiver {
40
41 private final File archive;
42
43
44
45
46 public TarUnArchiver(File archive) {
47 this.archive = archive;
48 }
49
50
51
52
53
54
55 public void unarchive(String baseDir) throws MojoExecutionException {
56 try (FileInputStream fis = new FileInputStream(archive);
57 TarArchiveInputStream tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(fis))) {
58 TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
59 while (tarEntry != null) {
60
61 final File destPath = new File(baseDir + File.separator + tarEntry.getName());
62 if (tarEntry.isSymbolicLink()) {
63 Path linkPath = destPath.toPath();
64 Path targetPath = new File(tarEntry.getLinkName()).toPath();
65 Files.createSymbolicLink(linkPath, targetPath);
66 }
67 else if (tarEntry.isDirectory()) {
68 destPath.mkdirs();
69 }
70 else {
71 destPath.createNewFile();
72 destPath.setExecutable(true);
73 try (BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath))) {
74 IOUtils.copy(tarIn, bout);
75 }
76 }
77 tarEntry = tarIn.getNextTarEntry();
78 }
79 }
80 catch (IOException ex) {
81 throw new MojoExecutionException("Could not extract archive: " + archive.getAbsolutePath(), ex);
82 }
83
84
85 archive.delete();
86 }
87
88 }