View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2019 wcm.io
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
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  
28  import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
29  import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
30  import org.apache.commons.io.IOUtils;
31  import org.apache.maven.plugin.MojoExecutionException;
32  
33  /**
34   * Wrapper around the commons compress library to decompress the zip archives
35   */
36  public class ZipUnArchiver {
37  
38    private final File archive;
39  
40    /**
41     * @param archive Archive
42     */
43    public ZipUnArchiver(File archive) {
44      this.archive = archive;
45    }
46  
47    /**
48     * Unarchives the archive into the base dir
49     * @param baseDir Base dir
50     * @throws MojoExecutionException Mojo execution exception
51     */
52    public void unarchive(String baseDir) throws MojoExecutionException {
53      try (FileInputStream fis = new FileInputStream(archive);
54          ZipArchiveInputStream zipIn = new ZipArchiveInputStream(fis)) {
55        ZipArchiveEntry zipEnry = zipIn.getNextZipEntry();
56        while (zipEnry != null) {
57          // Create a file for this tarEntry
58          final File destPath = new File(baseDir + File.separator + zipEnry.getName());
59          if (zipEnry.isDirectory()) {
60            destPath.mkdirs();
61          }
62          else {
63            destPath.createNewFile();
64            try (BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath))) {
65              IOUtils.copy(zipIn, bout);
66            }
67          }
68          zipEnry = zipIn.getNextZipEntry();
69        }
70      }
71      catch (IOException ex) {
72        throw new MojoExecutionException("Could not extract archive: " + archive.getAbsolutePath(), ex);
73      }
74  
75      // delete archive after extraction
76      archive.delete();
77    }
78  
79  }