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.ContentType;
22 import org.apache.hc.core5.http.HttpEntity;
23 import org.apache.hc.core5.http.io.entity.EntityUtils;
24
25 import java.io.IOException;
26 import java.nio.charset.Charset;
27
28 /**
29 * A responseHandler that uses an explicit client-defined characterset to interpret the response payload as a string.
30 *
31 * @author Hans Aikema
32 */
33 public class ExplicitCharsetToStringResponseHandler extends AbstractHttpClientResponseHandler<String> {
34
35 /**
36 * The explicit Charset used for interpreting the bytes of the HTTP response entity.
37 */
38 private final Charset charset;
39
40 /**
41 * Constructs a repsonse handler to transfor the binary contents received using the given Charset.
42 *
43 * @param charset The Charset to be used to transform a downloaded file into a String.
44 */
45 public ExplicitCharsetToStringResponseHandler(Charset charset) {
46 this.charset = charset;
47 }
48
49 @Override
50 public String handleEntity(HttpEntity entity) throws IOException {
51 final ContentType contentType;
52 contentType = ContentType.parseLenient(entity.getContentType());
53 if (contentType != null) {
54 final Charset entityCharset = contentType.getCharset();
55 if (entityCharset != null && !entityCharset.equals(charset)) {
56 throw new DownloadFailedException(
57 String.format("Requested decoding charset %s incompatible with the explicit response charset %s.", charset, entityCharset));
58 }
59 }
60 return new String(EntityUtils.toByteArray(entity), charset);
61 }
62 }