View Javadoc
1   /*
2    * This file is part of dependency-check-utils.
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   * Copyright (c) 2024 Hans Aikema. All Rights Reserved.
17   */
18  package org.owasp.dependencycheck.utils;
19  
20  import org.apache.hc.client5.http.impl.classic.AbstractHttpClientResponseHandler;
21  import org.apache.hc.core5.http.HttpEntity;
22  
23  import java.io.File;
24  import java.io.FileOutputStream;
25  import java.io.IOException;
26  import java.io.InputStream;
27  import java.nio.ByteBuffer;
28  import java.nio.channels.Channels;
29  import java.nio.channels.FileChannel;
30  import java.nio.channels.ReadableByteChannel;
31  
32  class SaveToFileResponseHandler extends AbstractHttpClientResponseHandler<Void> {
33  
34      /**
35       * The output path where the response content should be stored as a file
36       */
37      private final File outputPath;
38  
39      SaveToFileResponseHandler(File outputPath) {
40          this.outputPath = outputPath;
41      }
42  
43      @Override
44      public Void handleEntity(HttpEntity responseEntity) throws IOException {
45          try (InputStream in = responseEntity.getContent();
46               ReadableByteChannel sourceChannel = Channels.newChannel(in);
47               FileOutputStream fos = new FileOutputStream(outputPath);
48               FileChannel destChannel = fos.getChannel()) {
49              final ByteBuffer buffer = ByteBuffer.allocateDirect(8192);
50              while (sourceChannel.read(buffer) != -1) {
51                  buffer.flip();
52                  destChannel.write(buffer);
53                  buffer.compact();
54              }
55          }
56          return null;
57      }
58  
59  }