summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/pomba/contextaggregator/rest/RestRequest.java
blob: cacc8e677f4f5717a268ad92c489e0d061fe89bc (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
/*
 * ============LICENSE_START===================================================
 * Copyright (c) 2018 Amdocs
 * ============================================================================
 * 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.pomba.contextaggregator.rest;

import java.util.Base64;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import org.onap.aai.restclient.client.Headers;
import org.onap.aai.restclient.client.OperationResult;
import org.onap.aai.restclient.client.RestClient;
import org.onap.pomba.contextaggregator.builder.ContextBuilder;
import org.onap.pomba.contextaggregator.datatypes.POAEvent;
import org.onap.pomba.contextaggregator.exception.ContextAggregatorError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

public class RestRequest {

    private static final String SERVICE_INSTANCE_ID = "serviceInstanceId";
    private static final String MODEL_VERSION_ID = "modelVersionId";
    private static final String MODE_INVARIANT_ID = "modelInvariantId";
    private static final String CUSTOMER_ID = "customerId";
    private static final String SERVICE_TYPE = "serviceType";

    private static final String APP_NAME = "context-aggregator";

    private static Logger log = LoggerFactory.getLogger(RestRequest.class);


    private RestRequest() {
        // intentionally empty
    }

    /**
     * Retrieves the model data from the given context builder
     *
     * @param builder
     * @param event
     * @return Returns the JSON response from the context builder
     */
    public static String getModelData(ContextBuilder builder, POAEvent event) {
        RestClient restClient = createRestClient(builder);

        OperationResult result = restClient.get(generateUri(builder, event),
                generateHeaders(event.getxTransactionId(), builder), MediaType.APPLICATION_JSON_TYPE);

        if (result.wasSuccessful()) {
            log.debug("Retrieved model data for '" + builder.getContextName() + "': " + result.getResult());
            return result.getResult();
        } else {
            // failed! return null
            log.error(ContextAggregatorError.FAILED_TO_GET_MODEL_DATA.getMessage(builder.getContextName(),
                    result.getFailureCause()));
            log.debug("Failed to retrieve model data for '" + builder.getContextName());
            return null;
        }
    }

    private static RestClient createRestClient(ContextBuilder builder) {
        return new RestClient()
                // .validateServerHostname(false)
                // .validateServerCertChain(true)
                // .clientCertFile(builder.getKeyStorePath())
                // .clientCertPassword(builder.getKeyStorePassword())
                // .trustStore(builder.getTrustStorePath())
                .connectTimeoutMs(builder.getConnectionTimeout()).readTimeoutMs(builder.getReadTimeout());
    }

    private static String generateUri(ContextBuilder builder, POAEvent event) {
        UriComponents uriComponents = UriComponentsBuilder.newInstance().scheme(builder.getProtocol())
                .host(builder.getHost()).port(builder.getPort()).path(builder.getBaseUri())
                .queryParam(SERVICE_INSTANCE_ID, event.getServiceInstanceId())
                .queryParam(MODEL_VERSION_ID, event.getModelVersionId())
                .queryParam(MODE_INVARIANT_ID, event.getModelInvariantId())
                .queryParam(SERVICE_TYPE, event.getServiceType()).queryParam(CUSTOMER_ID, event.getCustomerId()).build()
                .encode();
        return uriComponents.toUriString();
    }

    private static Map<String, List<String>> generateHeaders(String transactionId, ContextBuilder builder) {
        MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
        headers.add(Headers.FROM_APP_ID, APP_NAME);
        headers.add(Headers.TRANSACTION_ID, transactionId);
        headers.add(Headers.AUTHORIZATION, getBasicAuthString(builder));
        return headers;
    }

    private static String getBasicAuthString(ContextBuilder builder) {
        String usernamePasswordString = builder.getUsername() + ":" + builder.getPassword();
        String encodedString = Base64.getEncoder().encodeToString((usernamePasswordString).getBytes());
        return "Basic " + encodedString;

    }
}