2 * ============LICENSE_START====================================
3 * DCAEGEN2-SERVICES-SDK
4 * =========================================================
5 * Copyright (C) 2019 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=====================================
21 package org.onap.dcaegen2.services.sdk.services.hvves.client.producer.api.options;
23 import io.vavr.control.Try;
25 import java.nio.ByteBuffer;
26 import java.nio.CharBuffer;
27 import java.nio.charset.Charset;
28 import java.nio.file.Files;
29 import java.nio.file.Path;
30 import java.nio.file.Paths;
31 import java.util.Arrays;
32 import org.jetbrains.annotations.NotNull;
35 * Utility functions for loading passwords.
37 * @author <a href="mailto:piotr.jaszczyk@nokia.com">Piotr Jaszczyk</a>
40 public final class Passwords {
45 public static @NotNull Try<Password> fromFile(File file) {
46 return fromPath(file.toPath());
49 public static @NotNull Try<Password> fromPath(Path path) {
51 final byte[] bytes = Files.readAllBytes(path);
52 final CharBuffer password = decodeChars(bytes);
53 final char[] result = convertToCharArray(password);
54 return new Password(result);
58 public static @NotNull Try<Password> fromResource(String resource) {
59 return Try.of(() -> Paths.get(Passwords.class.getResource(resource).toURI()))
60 .flatMap(Passwords::fromPath);
63 private static @NotNull CharBuffer decodeChars(byte[] bytes) {
65 return Charset.defaultCharset().decode(ByteBuffer.wrap(bytes));
67 Arrays.fill(bytes, (byte) 0);
71 private static char[] convertToCharArray(CharBuffer password) {
73 final char[] result = new char[password.limit()];
78 clearBuffer(password);
82 private static void clearBuffer(CharBuffer password) {
83 while (password.remaining() > 0) {
84 password.put((char) 0);