summaryrefslogtreecommitdiffstats
path: root/dcaedt_tools/src/main/java/utilities/DcaeRestClient.java
blob: e5505108b7589108fd24a1546adc7e7dda780339 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package utilities;

import json.Credential;
import json.Environment;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.ssl.SSLContextBuilder;
import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest;
import org.onap.sdc.dcae.composition.restmodels.canvas.DcaeComponentCatalog;
import org.onap.sdc.dcae.composition.restmodels.sdc.Resource;
import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import tools.LoggerDebug;

import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component("dcaerestclient")
public class DcaeRestClient implements IDcaeRestClient {

    private static LoggerDebug debugLogger = LoggerDebug.getInstance();
    private static final String GET_RESOURCES_BY_CATEGORY = "/getResourcesByCategory";
    private static final String CREATE_VFCMT = "/createVFCMT";
	private static final String CATALOG = "/catalog";


    private static final String ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID";
    private static final String USER_ID_HEADER = "USER_ID";


    private String uri;
    private RestTemplate client;
    private Credential credential;

    public DcaeRestClient(Credential credential) {
        this.credential = credential;
    }

    @Override
    public String getUserId() {
        return credential.getUsername();
    }

    @PostConstruct
    @Override
    public void init(Environment environment) {
        credential = environment.getCredential();
        debugLogger.log("Connecting to server host: " + environment.getDcaeBeHost() + ", port: " + environment.getDcaeBePort());
        try {
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
            requestFactory.setHttpClient(buildRestClient());
            client = new RestTemplate(requestFactory);
        } catch (SSLException e) {
            debugLogger.log("ERROR: Build rest client failed because: " + e.getMessage());
        }
        uri = String.format("%s:%s%s", environment.getDcaeBeHost(), environment.getDcaeBePort(), environment.getApiPath());
        debugLogger.log("end function");
    }

    private List<BasicHeader> defaultHeaders(Credential credential) {
        List<BasicHeader> headers = new ArrayList<>();
        headers.add(new BasicHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE));
        headers.add(new BasicHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM_VALUE));
        headers.add(new BasicHeader(ECOMP_INSTANCE_ID_HEADER, credential.getUsername()));
        return headers;
    }

    @Override
    public List<ResourceDetailed> getAllVfcmts() {
        String url = buildRequestPath(GET_RESOURCES_BY_CATEGORY);
        return Arrays.asList(client.getForObject(url, ResourceDetailed[].class));
    }

    @Override
    public List<ResourceDetailed> getAllBaseVfcmts() {
        String url = buildRequestPath("/getResourcesByMonitoringTemplateCategory");
        return Arrays.asList(client.getForObject(url, ResourceDetailed[].class));
    }

    @Override
    public ResourceDetailed createResource(CreateVFCMTRequest resource) {
        String url = buildRequestPath(CREATE_VFCMT);
        return client.postForObject(url, new HttpEntity<>(resource, postResourceHeaders(credential.getUsername())), ResourceDetailed.class);
    }

    @Override
    public ResourceDetailed checkoutVfcmt(String vfcmtUuid) {
        String url = buildRequestPath(String.format("/checkout/vfcmt/%s", vfcmtUuid));
        ResponseEntity<ResourceDetailed> resourceDetailedResponse = client.exchange(url, HttpMethod.PUT, new HttpEntity(postResourceHeaders(credential.getUsername())), ResourceDetailed.class);

        return resourceDetailedResponse.getBody();
    }

    @Override
    public ResourceDetailed checkinVfcmt(String vfcmtUuid) {
        String url = buildRequestPath(String.format("/checkin/vfcmt/%s", vfcmtUuid));
        ResponseEntity<ResourceDetailed> resourceDetailedResponse = client.exchange(url, HttpMethod.PUT, new HttpEntity(postResourceHeaders(credential.getUsername())), ResourceDetailed.class);

        return resourceDetailedResponse.getBody();
    }

	@Override
	public Map<String, List<Resource>> getDcaeCatalog() {
		String url = buildRequestPath(CATALOG);
		DcaeComponentCatalog catalog = client.getForObject(url, DcaeComponentCatalog.class);
		return catalog.getElements().stream().collect(Collectors.toMap(DcaeComponentCatalog.SubCategoryFolder::getName, DcaeComponentCatalog.SubCategoryFolder::getItems));
	}


    @Override
    public String getItemModel(String elementId) {
        String url = buildRequestPath("/"+ elementId +"/model");
        return client.getForObject(url, String.class);
    }
    @Override
    public String getItemType(String elementId, String type) {
        String url = buildRequestPath("/"+ elementId +"/type/"+ type +"/");
        return client.getForObject(url, String.class);
    }

    @Override
    public String saveComposition(String componentId, String body) {
        String url = buildRequestPath("/saveComposition/" + componentId);
        ResponseEntity<String> resourceDetailedResponse = client.exchange(url, HttpMethod.POST, new HttpEntity<>(body, postResourceHeaders(credential.getUsername())), String.class);

        return resourceDetailedResponse.getBody();
    }

    @Override
    public String certifyVfcmt(String vfcmtUuid) {
        String url = buildRequestPath(String.format("/certify/vfcmt/%s", vfcmtUuid));
        ResponseEntity<String> resourceDetailedResponse = client.exchange(url, HttpMethod.PUT, new HttpEntity(postResourceHeaders(credential.getUsername())), String.class);

        return resourceDetailedResponse.getBody();
    }

    private HttpHeaders postResourceHeaders(String userId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add(USER_ID_HEADER, userId);
        return headers;
    }

    private String buildRequestPath(String... args){
        String url = uri + String.join("", args);
        debugLogger.log("Sending request: " + url);
        return url;
    }

    @Override
    public void updateResource(ResourceDetailed vfcmt) {
        // Do nothing
    }

    private CloseableHttpClient buildRestClient() throws SSLException {
        SSLContextBuilder builder = new SSLContextBuilder();
        try {
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                SSLContext.getDefault(), NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry =
                RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory()).register("https", sslsf)
                    .build();
            PoolingHttpClientConnectionManager cm =
                new PoolingHttpClientConnectionManager(registry);
            return HttpClients.custom().setSSLSocketFactory(sslsf).setConnectionManager(cm).build();
        } catch (NoSuchAlgorithmException | KeyStoreException e) {
            throw new SSLException(e);
        }
    }
}