View Javadoc
1   /*
2    * Copyright 2022 The Apache Software Foundation
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  package org.codehaus.plexus.archiver.zstd;
17  
18  import java.io.BufferedOutputStream;
19  import java.io.IOException;
20  
21  import org.apache.commons.compress.compressors.zstandard.ZstdCompressorOutputStream;
22  import org.codehaus.plexus.archiver.ArchiverException;
23  import org.codehaus.plexus.archiver.util.Compressor;
24  
25  import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream;
26  import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream;
27  
28  /**
29   * Zstd compression
30   */
31  public class ZstdCompressor extends Compressor {
32  
33      private Integer level;
34  
35      private ZstdCompressorOutputStream zstdOut;
36  
37      public ZstdCompressor() {}
38  
39      public void setLevel(Integer level) {
40          this.level = level;
41      }
42  
43      @Override
44      public void compress() throws ArchiverException {
45          try {
46              BufferedOutputStream outStream = bufferedOutputStream(fileOutputStream(getDestFile()));
47              if (level == null) {
48                  zstdOut = new ZstdCompressorOutputStream(outStream);
49              } else {
50                  zstdOut = new ZstdCompressorOutputStream(outStream, level);
51              }
52              compress(getSource(), zstdOut);
53          } catch (IOException ioe) {
54              throw new ArchiverException("Problem creating zstd " + ioe.getMessage(), ioe);
55          }
56      }
57  
58      @Override
59      public void close() {
60          try {
61              if (this.zstdOut != null) {
62                  this.zstdOut.close();
63                  zstdOut = null;
64              }
65          } catch (final IOException e) {
66              throw new ArchiverException("Failure closing target.", e);
67          }
68      }
69  }