summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/dcae/controller/AccessController.java
blob: 83673b86f791dafbf6625fdc892469e4e38e53cc (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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*-
 * ============LICENSE_START=======================================================
 * org.onap.dcaegen2.collectors.restconf
 * ================================================================================
 * Copyright (C) 2018-2019 Huawei. 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 org.onap.dcae.controller;

import org.json.JSONArray;
import org.json.JSONObject;
import org.onap.dcae.ApplicationException;
import org.onap.dcae.ApplicationSettings;
import org.onap.dcae.common.Constants;
import org.onap.dcae.common.RestConfContext;
import org.onap.dcae.common.RestapiCallNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.nio.file.Files.readAllBytes;
import static org.onap.dcae.common.RestapiCallNodeUtil.getUriMethod;

public class AccessController {
    private static final Logger log = LoggerFactory.getLogger(AccessController.class);
    /* Collector properties */
    private ApplicationSettings properties;

    /* Controller specific information */
    private ControllerConfigInfo cfgInfo;
    private RestConfContext ctx;
    RestapiCallNode restApiCallNode;

    /* Maps of Events */
    private Map<String, PersistentEventConnection> eventList = new ConcurrentHashMap<>();
    private ExecutorService executor = Executors.newCachedThreadPool();
    private Map<String, String> paraMap;

    public AccessController(JSONObject controller,
                            ApplicationSettings properties) {
        this.cfgInfo = new ControllerConfigInfo(controller.get("controller_name").toString(),
                controller.get("controller_restapiUrl").toString(),
                controller.get("controller_restapiUser").toString(),
                controller.get("controller_restapiPassword").toString(),
                controller.get("controller_accessTokenUrl").toString(),
                controller.get("controller_accessTokenFile").toString(),
                controller.get("controller_subscriptionUrl").toString(),
                controller.get("controller_accessTokenMethod").toString(),
                controller.get("controller_subsMethod").toString());
        this.properties = properties;
        this.ctx = new RestConfContext();
        this.restApiCallNode = new RestapiCallNode();
        this.paraMap = new HashMap<>();

        prepareControllerParamMap();

        log.info("AccesController Created {} {} {} {} {} {}",
                this.cfgInfo.getController_name(),
                this.cfgInfo.getController_restapiUrl(),
                this.cfgInfo.getController_restapiPassword(),
                this.cfgInfo.getController_restapiUser(),
                this.cfgInfo.getController_accessTokenUrl(),
                this.cfgInfo.getController_accessTokenFile());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof AccessController)) return false;
        AccessController that = (AccessController) o;
        return that.cfgInfo.getController_name().equals(that.cfgInfo.getController_name());
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.cfgInfo.getController_name());
    }

    public RestapiCallNode getRestApiCallNode() {
        return restApiCallNode;
    }

    private void fetch_TokenId() {


        modifyControllerParamMap(Constants.KSETTING_REST_API_URL, getUriMethod(this.properties.authorizationEnabled()) + cfgInfo.getController_restapiUrl() + cfgInfo.getController_accessTokenUrl());
        modifyControllerParamMap(Constants.KDEFAULT_TEMP_FILENAME, cfgInfo.getController_accessTokenFile());
        modifyControllerParamMap(Constants.KSETTING_REST_UNAME, cfgInfo.getController_restapiUser());
        modifyControllerParamMap(Constants.KSETTING_REST_PASSWORD, cfgInfo.getController_restapiPassword());
        modifyControllerParamMap(Constants.KSETTING_HTTP_METHOD, cfgInfo.getController_accessTokenMethod());

        String httpResponse = null;
        try {

            restApiCallNode.sendRequest(this.paraMap, ctx, null);
            String key = getControllerParamMapValue(Constants.KSETTING_RESP_PREFIX).concat(".").concat("httpResponse");
            httpResponse = ctx.getAttribute(key);
            log.info("httpResponse ", httpResponse + " key " + key);
            JSONObject jsonObj = new JSONObject(httpResponse);
            log.info("jsonObj ", jsonObj.toString());
            //JSONObject data = jsonObj.getJSONObject("data");
            //String tokenId = data.get("accessSession").toString();
            //@TODO: Make return field dynamic
            String tokenId = jsonObj.get("accessSession").toString();
            log.info("token 1" + tokenId);
            modifyControllerParamMap(Constants.KSETTING_TOKENID, tokenId);
            modifyControllerParamMap(Constants.KSETTING_CUSTOMHTTP_HEADER, "X-ACCESS-TOKEN=" + tokenId);
        } catch (Exception e) {
            log.info("Access token is not supported" + e.getMessage());
            log.info("http response " + httpResponse);
        }
    }

    public void activate() {
        fetch_TokenId();
        printControllerParamMap();
        /* Create eventlist from properties */
        JSONArray contollers = new JSONArray(properties.rcc_policy());
        for (int i = 0; i < contollers.length(); i++) {
            JSONObject controller = contollers.getJSONObject(i);
            if (controller.get("controller_name").equals(this.getCfgInfo().getController_name())) {
                JSONArray eventlists = controller.getJSONArray("event_details");
                for (int j = 0; j < eventlists.length(); j++) {
                    JSONObject event = eventlists.getJSONObject(j);
                    String name = event.get("event_name").toString();
                    PersistentEventConnection conn = new PersistentEventConnection(name,
                            event.get("event_description").toString(),
                            Boolean.parseBoolean(event.get("event_sseventUrlEmbed").toString()),
                            event.get("event_sseventsField").toString(),
                            event.get("event_sseventsUrl").toString(),
                            event.get("event_subscriptionTemplate").toString(),
                            event.get("event_unSubscriptionTemplate").toString(),
                            event.get("event_ruleId").toString(),
                            this);

                    eventList.put(name, conn);
                    executor.execute(conn);
                }
            }
        }
    }

    public RestConfContext getCtx() {
        return ctx;
    }

    public ApplicationSettings getProperties() {
        return properties;
    }

    public ControllerConfigInfo getCfgInfo() {
        return cfgInfo;
    }

    public Map<String, String> getParaMap() {
        return this.paraMap;
    }

    private void prepareControllerParamMap() {
        /* Adding the fields in ParaMap */
        paraMap.put(Constants.KDEFAULT_TEMP_FILENAME, null);
        paraMap.put(Constants.KSETTING_REST_API_URL, null);
        paraMap.put(Constants.KSETTING_HTTP_METHOD, "post");
        paraMap.put(Constants.KSETTING_RESP_PREFIX, "responsePrefix");
        paraMap.put(Constants.KSETTING_SKIP_SENDING, "false");
        paraMap.put(Constants.KSETTING_SSE_CONNECT_URL, null);
        paraMap.put(Constants.KSETTING_FORMAT, "json");

        paraMap.put(Constants.KSETTING_REST_UNAME, null);
        paraMap.put(Constants.KSETTING_REST_PASSWORD, null);
        paraMap.put(Constants.KDEFAULT_REQUESTBODY, null);

        paraMap.put(Constants.KSETTING_AUTH_TYPE, "unspecified");
        paraMap.put(Constants.KSETTING_CONTENT_TYPE, "application/json");
        paraMap.put(Constants.KSETTING_OAUTH_CONSUMER_KEY, null);
        paraMap.put(Constants.KSETTING_OAUTH_CONSUMER_SECRET, null);
        paraMap.put(Constants.KSETTING_OAUTH_SIGNATURE_METHOD, null);
        paraMap.put(Constants.KSETTING_OAUTH_VERSION, null);

        paraMap.put(Constants.KSETTING_CUSTOMHTTP_HEADER, null);
        paraMap.put(Constants.KSETTING_TOKENID, null);
        paraMap.put(Constants.KSETTING_DUMP_HEADER, "false");
        paraMap.put(Constants.KSETTING_RETURN_REQUEST_PAYLOAD, "false");

        paraMap.put(Constants.KSETTING_TRUST_STORE_FILENAME, this.getProperties().truststoreFileLocation());
        String trustPassword = getKeyStorePassword(toAbsolutePath(this.getProperties().truststorePasswordFileLocation()));
        paraMap.put(Constants.KSETTING_TRUST_STORE_PASSWORD, trustPassword);
        paraMap.put(Constants.KSETTING_KEY_STORE_FILENAME, this.getProperties().keystoreFileLocation());
        String KeyPassword = getKeyStorePassword(toAbsolutePath(this.getProperties().keystorePasswordFileLocation()));
        paraMap.put(Constants.KSETTING_KEY_STORE_PASSWORD, KeyPassword);

    }

    private Path toAbsolutePath(final String path) {
        return Paths.get(path).toAbsolutePath();
    }

    private String getKeyStorePassword(final Path location) {
        try {
            return new String(readAllBytes(location));
        } catch (Exception e) {
            log.error("Could not read password from: '" + location + "'.", e);
            throw new ApplicationException(e);
        }
    }

    public void modifyControllerParamMap(String fieldName, String value) {
        paraMap.put(fieldName, value);
    }

    public String getControllerParamMapValue(String fieldName) {
        return paraMap.get(fieldName);
    }

    public void printControllerParamMap() {
        log.info("----------------Controller Param Map-------------------");
        for (String name : paraMap.keySet()) {
            String value = paraMap.get(name);
            log.info(name + " : " + value);
        }
    }
}