summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/pomba/contextaggregator/rest/RestRequest.java
blob: c4f1eef2183949dbbc8d37d8ecfc7026e264b6ef (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
/*
 * ============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.eclipse.jetty.util.security.Password;
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.onap.pomba.contextaggregator.exception.ContextAggregatorException;
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 MODEL_INVARIANT_ID = "modelInvariantId";

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

    private static final String BASIC_AUTH = "Basic ";

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


    private RestRequest() {
        // intentionally empty
    }

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

        OperationResult result;
        
        try {
            result = restClient.get(generateUri(builder, event), generateHeaders(event.getxTransactionId(), builder),
                    MediaType.APPLICATION_JSON_TYPE);
        } catch (Exception e) {
            log.error("Exception in Rest call", e);
            throw new ContextAggregatorException(ContextAggregatorError.FAILED_TO_GET_MODEL_DATA,
                    builder.getContextName(), e.getMessage());
        }

        if (result == null) {
            throw new ContextAggregatorException(ContextAggregatorError.FAILED_TO_GET_MODEL_DATA,
                    builder.getContextName(), "Null result");
        }
        if (result.wasSuccessful()) {
            log.info("Retrieved model data for '{}' context builder. Result: {}", builder.getContextName(), result.getResult());
            return result.getResult();
        }
        // failed! throw Exception:
        throw new ContextAggregatorException(ContextAggregatorError.FAILED_TO_GET_MODEL_DATA, builder.getContextName(),
                result.getFailureCause());

    }

    private static RestClient createRestClient(ContextBuilder builder) {
        return new RestClient()
                .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(MODEL_INVARIANT_ID, event.getModelInvariantId()).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 encodedString = Base64.getEncoder()
                .encodeToString((builder.getUsername() + ":" + Password.deobfuscate(builder.getPassword())).getBytes());
        return BASIC_AUTH + encodedString;

    }
}