Config fetch for VESCollector through DCAE-SDK (CBS Client)
[dcaegen2/collectors/ves.git] / src / test / java / org / onap / dcae / TestingUtilities.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.onap.dcaegen2.collectors.ves
4  * ================================================================================
5  * Copyright (C) 2018,2020 Nokia. All rights reserved.
6  * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.dcae;
22
23 import io.vavr.control.Try;
24 import org.apache.http.client.HttpClient;
25 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
26 import org.apache.http.impl.client.HttpClients;
27 import org.apache.http.ssl.SSLContextBuilder;
28 import org.assertj.core.api.AbstractThrowableAssert;
29 import org.assertj.core.api.Java6Assertions;
30 import org.json.JSONObject;
31 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
32 import org.springframework.web.client.RestTemplate;
33
34 import javax.net.ssl.SSLContext;
35 import java.io.File;
36 import java.io.FileInputStream;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.security.KeyStore;
41
42 import static java.nio.file.Files.readAllBytes;
43 import static org.assertj.core.api.Assertions.assertThat;
44
45 /**
46  * @author Pawel Szalapski (pawel.szalapski@nokia.com)
47  */
48 public final class TestingUtilities {
49
50     private TestingUtilities() {
51         // utility class, no objects allowed
52     }
53
54     public static void assertJSONObjectsEqual(JSONObject o1, JSONObject o2) {
55         assertThat(o1.toString()).isEqualTo(o2.toString());
56     }
57
58     public static JSONObject readJSONFromFile(Path path) {
59         return rethrow(() -> new JSONObject(readFile(path)));
60     }
61
62     public static String readFile(Path path) {
63         return rethrow(() -> new String(readAllBytes(path)));
64     }
65
66     public static Path createTemporaryFile(String content) {
67         return rethrow(() -> {
68             File temp = File.createTempFile("ves-collector-tests-created-this-file", ".tmp");
69             temp.deleteOnExit();
70             Path filePath = Paths.get(temp.toString());
71             Files.write(filePath, content.getBytes());
72             return filePath;
73         });
74     }
75
76     /**
77      * Exception in test case usually means there is something wrong, it should never be catched, but rather thrown to
78      * be handled by JUnit framework.
79      */
80     public static <T> T rethrow(CheckedSupplier<T> supplier) {
81         try {
82             return supplier.get();
83         } catch (Exception e) {
84             throw new RuntimeException(e);
85         }
86     }
87
88     @FunctionalInterface
89     interface CheckedSupplier<T> {
90
91         T get() throws Exception;
92     }
93
94     public static void assertFailureHasInfo(Try any, String... msgPart) {
95         Java6Assertions.assertThat(any.isFailure()).isTrue();
96         AbstractThrowableAssert<?, ? extends Throwable> o = Java6Assertions.assertThat(any.getCause())
97                 .hasCauseInstanceOf(Exception.class);
98         for (String s : msgPart) {
99             o.hasStackTraceContaining(s);
100         }
101     }
102
103     public static SSLContextBuilder sslBuilderWithTrustStore(final Path trustStore, final String pass) {
104         return rethrow(() ->
105                 new SSLContextBuilder()
106                         .loadTrustMaterial(trustStore.toFile(), pass.toCharArray())
107         );
108     }
109
110     public static SSLContextBuilder configureKeyStore(
111             final SSLContextBuilder builder,
112             final Path keyStore,
113             final String pass) {
114         return rethrow(() -> {
115             KeyStore cks = KeyStore.getInstance(KeyStore.getDefaultType());
116             cks.load(new FileInputStream(keyStore.toFile()), pass.toCharArray());
117
118             builder.loadKeyMaterial(cks, pass.toCharArray());
119
120             return builder;
121         });
122     }
123
124     public static RestTemplate createRestTemplateWithSsl(final SSLContext context) {
125         final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context);
126         final HttpClient httpClient = HttpClients
127                 .custom()
128                 .setSSLSocketFactory(socketFactory)
129                 .build();
130
131         final HttpComponentsClientHttpRequestFactory factory =
132                 new HttpComponentsClientHttpRequestFactory(httpClient);
133
134         return new RestTemplate(factory);
135     }
136 }