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              ZstdCompressorOutputStream.Builder zstdOutBuilder = ZstdCompressorOutputStream.builder();
48              zstdOutBuilder.setOutputStream(outStream);
49              if (level != null) {
50                  zstdOutBuilder.setLevel(level);
51              }
52              zstdOut = zstdOutBuilder.get();
53              compress(getSource(), zstdOut);
54          } catch (IOException ioe) {
55              throw new ArchiverException("Problem creating zstd " + ioe.getMessage(), ioe);
56          }
57      }
58  
59      @Override
60      public void close() {
61          try {
62              if (this.zstdOut != null) {
63                  this.zstdOut.close();
64                  zstdOut = null;
65              }
66          } catch (final IOException e) {
67              throw new ArchiverException("Failure closing target.", e);
68          }
69      }
70  }