aboutsummaryrefslogtreecommitdiffstats
path: root/cps-tbdmt-service/src/main/java/org/onap/cps/tbdmt/client/CpsRestClient.java
blob: e1301fb5ed2d7e790d9fd4d13adb3e5da376f34c (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
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2021 Wipro Limited.
 * ================================================================================
 * 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 org.onap.cps.tbdmt.client;

import java.util.Arrays;
import java.util.Map;
import org.onap.cps.tbdmt.exception.CpsClientException;
import org.onap.cps.tbdmt.model.AppConfiguration;
import org.onap.cps.tbdmt.model.CpsConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

@Component
public class CpsRestClient {

    private static final String NODES_API_PATH = "/anchors/{anchor}/node";

    private static final String QUERY_API_PATH = "/anchors/{anchor}/nodes/query";

    private static final String POST_API_PATH = "/anchors/{anchor}/nodes";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private AppConfiguration appConfiguration;

    /**
     * Fetch node from the CPS using xpath.
     *
     * @param anchor anchor
     * @param xpath xpath query
     * @return result Response string from CPS
     */
    public String fetchNode(final String anchor, final String xpath,
        final String requestType, final Boolean includeDescendants) throws CpsClientException {
        final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
        queryParams.add("xpath", xpath);
        queryParams.add("include-descendants", includeDescendants.toString());

        final CpsConfiguration cpsConfiguration = "cpsCore".equals(appConfiguration.getCpsClient())
            ? appConfiguration.getCpsCoreConfiguration() : appConfiguration.getNcmpConfiguration();

        final String path = "query".equals(requestType) ? QUERY_API_PATH : NODES_API_PATH;
        final String uri = buildCpsUrl(cpsConfiguration.getUrl(), path, anchor, queryParams);

        final HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

        headers.setBasicAuth(cpsConfiguration.getUsername(), cpsConfiguration.getPassword());
        final HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
        } catch (final Exception e) {
            throw new CpsClientException(e.getLocalizedMessage());
        }

        final int statusCode = responseEntity.getStatusCodeValue();

        if (statusCode == 200) {
            return responseEntity.getBody();
        } else {
            throw new CpsClientException(
                String.format("Response code from CPS other than 200: %d", statusCode));
        }
    }

    /**
     * Post data to CPS using xpath.
     *
     * @param anchor anchor
     * @param xpath xpath query
     * @param requestType http request type
     * @param payload request body
     * @return result Response string from CPS
     */
    public String addData(final String anchor, final String xpath, final String requestType,
            final Map<String, Object> payload) throws CpsClientException {

        final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
        queryParams.add("xpath", xpath);
        final CpsConfiguration cpsConfiguration = "cpsCore".equals(appConfiguration.getCpsClient())
            ? appConfiguration.getCpsCoreConfiguration() : appConfiguration.getNcmpConfiguration();

        final HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBasicAuth(cpsConfiguration.getUsername(), cpsConfiguration.getPassword());
        final HttpEntity<String> entity = new HttpEntity<>(new com.google.gson.Gson().toJson(payload), headers);

        String uri = buildCpsUrl(cpsConfiguration.getUrl(), POST_API_PATH, anchor, queryParams);
        try {
            if (requestType.equalsIgnoreCase("post")) {
                uri = buildCpsUrl(cpsConfiguration.getUrl(), POST_API_PATH, anchor, new LinkedMultiValueMap<>());
                return restTemplate.postForEntity(uri, entity, String.class).getBody();
            } else if (requestType.equalsIgnoreCase("patch")) {
                final HttpComponentsClientHttpRequestFactory requestFactory
                        = new HttpComponentsClientHttpRequestFactory();
                requestFactory.setConnectTimeout(10000);
                requestFactory.setReadTimeout(10000);
                restTemplate.setRequestFactory(requestFactory);
                return restTemplate.patchForObject(uri, entity, String.class);
            } else {
                return restTemplate.exchange(uri, HttpMethod.PUT, entity, String.class).getBody();
            }
        } catch (final Exception e) {
            throw new CpsClientException(e.getLocalizedMessage());
        }
    }

    private String buildCpsUrl(final String baseUrl, final String path, final String anchor,
        final MultiValueMap<String, String> queryParams) {

        return UriComponentsBuilder
            .fromHttpUrl(baseUrl)
            .path(path)
            .queryParams(queryParams)
            .buildAndExpand(anchor)
            .toUriString();
    }

}