Merge "Replace SO client"
[vid.git] / vid-app-common / src / test / java / org / onap / vid / asdc / rest / SdcRestClientITTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2018 Nokia Intellectual Property. 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.vid.asdc.rest;
22
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.xebialabs.restito.semantics.Call;
25 import org.apache.http.config.Registry;
26 import org.apache.http.config.RegistryBuilder;
27 import org.apache.http.conn.socket.ConnectionSocketFactory;
28 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
29 import org.apache.http.conn.ssl.SSLContextBuilder;
30 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
31 import org.apache.http.impl.client.CloseableHttpClient;
32 import org.apache.http.impl.client.HttpClientBuilder;
33 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
34 import org.junit.AfterClass;
35 import org.junit.BeforeClass;
36 import org.junit.Test;
37 import org.onap.vid.asdc.AsdcCatalogException;
38 import org.onap.vid.asdc.beans.Service;
39 import org.onap.vid.client.SyncRestClient;
40 import org.onap.vid.testUtils.StubServerUtil;
41
42 import javax.net.ssl.SSLContext;
43 import java.io.IOException;
44 import java.nio.file.Files;
45 import java.nio.file.Path;
46 import java.security.GeneralSecurityException;
47 import java.util.Collections;
48 import java.util.Optional;
49 import java.util.UUID;
50
51 import static com.xebialabs.restito.semantics.Action.ok;
52 import static com.xebialabs.restito.semantics.Action.stringContent;
53 import static org.apache.http.client.config.RequestConfig.custom;
54 import static org.hamcrest.MatcherAssert.assertThat;
55 import static org.hamcrest.Matchers.hasItems;
56 import static org.hamcrest.Matchers.is;
57 import static org.hamcrest.Matchers.matchesPattern;
58 import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
59 import static org.junit.Assert.assertTrue;
60 import static org.onap.vid.client.SyncRestClientInterface.HEADERS.X_ECOMP_INSTANCE_ID;
61 import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY;
62
63
64 public class SdcRestClientITTest {
65     private static final String UUID_REGEX = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
66     private static final String[] SUPPORTED_SSL_VERSIONS = {"TLSv1", "TLSv1.2"};
67     private static StubServerUtil stubServer;
68     private static SdcRestClient sdcRestClient;
69
70     @BeforeClass
71     public static void setUpClass() throws GeneralSecurityException {
72         stubServer = new StubServerUtil();
73         stubServer.runSecuredServer();
74         SyncRestClient syncRestClient = new SyncRestClient(createNaiveHttpClient());
75         String serverUrl = stubServer.constructTargetUrl("https", "");
76         sdcRestClient = new SdcRestClient(serverUrl, "", syncRestClient);
77     }
78
79     @AfterClass
80     public static void tearDown() {
81         stubServer.stopServer();
82     }
83
84     @Test
85     public void shouldDownloadToscaArtifactUsingSecuredEndpoint() throws AsdcCatalogException, IOException {
86         UUID uuid = UUID.randomUUID();
87         String expectedEndpoint = String.format("/sdc/v1/catalog/services/%s/toscaModel", uuid);
88
89         stubServer.prepareGetCall(
90                 expectedEndpoint, stringContent("sampleFileContent"), "sampleFileContent", ok(), "application/octet-stream");
91
92
93         Path serviceToscaModel = sdcRestClient.getServiceToscaModel(uuid);
94         serviceToscaModel.toFile().deleteOnExit();
95
96
97         assertThat(Files.readAllLines(serviceToscaModel), contains("sampleFileContent"));
98         assertThatRequestHasRequiredHeaders(expectedEndpoint);
99     }
100
101     @Test
102     public void shouldGetServiceDetailsUsingSecuredEndpoint() throws AsdcCatalogException, JsonProcessingException {
103         UUID uuid = UUID.randomUUID();
104         String expectedEndpoint = String.format("/sdc/v1/catalog/services/%s/metadata", uuid);
105         Service expectedService = getExpectedService(uuid.toString());
106
107
108         stubServer.prepareGetCall(expectedEndpoint, expectedService, ok());
109
110
111         Service actualService = sdcRestClient.getService(uuid);
112
113
114         assertThat(actualService, is(expectedService));
115         assertThatRequestHasRequiredHeaders(expectedEndpoint);
116     }
117
118     private void assertThatRequestHasRequiredHeaders(String expectedEndpoint) {
119         Optional<Call> first = stubServer
120                 .getServerCalls()
121                 .stream()
122                 .filter(x -> x.getUri().contains(expectedEndpoint))
123                 .findFirst();
124
125         assertTrue(first.isPresent());
126
127         assertThat(first.get().getHeaders().keySet(), hasItems(X_ECOMP_INSTANCE_ID.toLowerCase(), REQUEST_ID_HEADER_KEY.toLowerCase()));
128         assertThat(first.get().getHeaders().get(REQUEST_ID_HEADER_KEY.toLowerCase()).get(0), matchesPattern(UUID_REGEX));
129     }
130
131     private Service getExpectedService(String stringId) {
132         return new Service(stringId, stringId,
133                 "sampleCategory", "sampleVersion",
134                 "sampleName", "sampleDistStatus",
135                 "sampleToscaUrl", Service.LifecycleState.CERTIFIED, Collections.emptyList(), Collections.emptyList());
136     }
137
138
139     private static CloseableHttpClient createNaiveHttpClient() throws GeneralSecurityException {
140         final SSLContext context = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
141                 .build();
142
143         final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context, SUPPORTED_SSL_VERSIONS,
144                 null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
145         Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
146                 .register("https", socketFactory)
147                 .build();
148
149         return HttpClientBuilder.create()
150                 .setDefaultRequestConfig(custom().setConnectionRequestTimeout(10000).build())
151                 .setConnectionManager(new PoolingHttpClientConnectionManager(registry))
152                 .setSSLSocketFactory(socketFactory).build();
153     }
154 }