9f534d8f567ec38566758b8cf55bf68f7b05ae83
[dcaegen2/services/sdk.git] /
1 /*
2  * ============LICENSE_START====================================
3  * DCAEGEN2-SERVICES-SDK
4  * =========================================================
5  * Copyright (C) 2019-2021 Nokia. All rights reserved.
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  * ============LICENSE_END=====================================
19  */
20
21 package org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.impl;
22
23 import io.vavr.Tuple;
24 import io.vavr.Tuple2;
25 import io.vavr.control.Option;
26 import org.onap.dcaegen2.services.sdk.model.streams.AafCredentials;
27 import org.onap.dcaegen2.services.sdk.rest.services.adapters.http.HttpResponse;
28
29 import java.nio.charset.StandardCharsets;
30 import java.util.Base64;
31 import java.util.Objects;
32
33 /**
34  * @author <a href="mailto:piotr.jaszczyk@nokia.com">Piotr Jaszczyk</a>
35  * @since April 2019
36  */
37 final class Commons {
38
39     private Commons() {
40     }
41
42     static String extractFailReason(HttpResponse httpResponse) {
43         return String.format("%d %s%n%s", httpResponse.statusCode(), httpResponse.statusReason(),
44                 httpResponse.bodyAsString());
45     }
46
47     static Tuple2<String, String> basicAuthHeader(AafCredentials credentials) {
48         Objects.requireNonNull(credentials, "aafCredentials");
49         String basicAuthFormat = basicAuthFormat(credentials);
50         byte[] utf8 = bytesUTF8(basicAuthFormat);
51         String userCredentials = Base64.getEncoder().encodeToString(utf8);
52         return Tuple.of("Authorization", "Basic " + userCredentials);
53     }
54
55     private static String basicAuthFormat(AafCredentials credentials) {
56         String username = getOrEmpty(credentials.username());
57         String password = getOrEmpty(credentials.password());
58         return username.concat(":").concat(password);
59     }
60
61     private static String getOrEmpty(String text) {
62         return Option.of(text).getOrElse("");
63     }
64
65     private static byte[] bytesUTF8(String text) {
66         return Option.of(text)
67                 .map(s -> s.getBytes(StandardCharsets.UTF_8))
68                 .getOrElse(new byte[0]);
69     }
70 }