aboutsummaryrefslogtreecommitdiffstats
path: root/sdnr/northbound/addCMHandle/provider/src/main/java/org/onap/ccsdk/features/sdnr/northbound/addCMHandle/AddCMHandleProvider.java
blob: 1756615cbe8730ece79b01b28b20b59c27cf55db (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
/*-
 * ============LICENSE_START=======================================================
 * ONAP : CCSDK
 * ================================================================================
 * 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.ccsdk.features.sdnr.northbound.addCMHandle;

import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION;

import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.ListenableFuture;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.MediaType;

import org.eclipse.jdt.annotation.NonNull;
import org.json.JSONObject;
import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfAccessor;
import org.onap.ccsdk.features.sdnr.wt.netconfnodestateservice.NetconfNodeStateListener;
import org.onap.ccsdk.sli.core.sli.provider.MdsalHelper;
import org.opendaylight.mdsal.binding.api.DataBroker;
import org.opendaylight.mdsal.binding.api.DataObjectModification;
import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
import org.opendaylight.mdsal.binding.api.DataTreeModification;
import org.opendaylight.mdsal.binding.api.NotificationPublishService;
import org.opendaylight.mdsal.binding.api.RpcProviderService;
import org.opendaylight.mdsal.dom.api.DOMDataBroker;
import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev210615.AddCMHandleInput;
import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev210615.AddCMHandleOutput;
import org.opendaylight.yang.gen.v1.org.onap.ccsdk.rev210615.CMHandleAPIService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.concepts.ObjectRegistration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AddCMHandleProvider implements CMHandleAPIService, NetconfNodeStateListener, AutoCloseable {

    private static final Logger LOG = LoggerFactory.getLogger(AddCMHandleProvider.class);
    private final String APPLICATION_NAME = "addCMHandle";
    private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR";
    private static final String PROPERTIES_FILE_NAME = "cm-handle.properties";
    private static final String PARSING_ERROR =
            "Could not create the request message to send to the server; no message will be sent";
    private final ExecutorService executor;
    protected DataBroker dataBroker;
    protected DOMDataBroker domDataBroker;
    protected NotificationPublishService notificationService;
    protected RpcProviderService rpcProviderRegistry;
    private ObjectRegistration<CMHandleAPIService> rpcRegistration;
    public static final InstanceIdentifier<Topology> NETCONF_TOPO_IID = InstanceIdentifier.create(NetworkTopology.class)
            .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
    private static HashMap<String, String> config;

    public AddCMHandleProvider() {

        LOG.info("Creating provider for {}", APPLICATION_NAME);
        executor = Executors.newFixedThreadPool(1);
        this.dataBroker = null;
        this.domDataBroker = null;
        this.notificationService = null;
        this.rpcProviderRegistry = null;
        this.rpcRegistration = null;
    }

    public void setDataBroker(DataBroker dataBroker) {
        this.dataBroker = dataBroker;
    }

    public void setDomDataBroker(DOMDataBroker domDataBroker) {
        this.domDataBroker = domDataBroker;
    }

    public void setRpcProviderRegistry(RpcProviderService rpcProviderRegistry) {
        this.rpcProviderRegistry = rpcProviderRegistry;
    }

    public void setNotificationPublishService(NotificationPublishService notificationPublishService) {
        this.notificationService = notificationPublishService;
    }

    public void init() {
        LOG.info("Initializing {} for {}", this.getClass().getName(), APPLICATION_NAME);

        if (rpcRegistration == null) {
            if (rpcProviderRegistry != null) {
                rpcRegistration = rpcProviderRegistry.registerRpcImplementation(CMHandleAPIService.class, this);
                LOG.info("Initialization complete for {}", APPLICATION_NAME);
            } else {
                LOG.warn("Error initializing {} : rpcRegistry unset", APPLICATION_NAME);
            }
        }

        String propDir = System.getenv(SDNC_CONFIG_DIR);
        if (propDir == null) {
            LOG.error("Environment variable SDNC_CONFIG_DIR is not set");
            propDir = "/opt/onap/ccsdk/data/properties/";
        } else if (!propDir.endsWith("/")) {
            propDir = propDir + "/";
        }

        // GET configuration from properties file
        config = new HashMap<String, String>();

        try {
            FileInputStream fileInput = new FileInputStream(propDir + PROPERTIES_FILE_NAME);
            Properties properties = new Properties();
            properties.load(fileInput);
            fileInput.close();

            for (String param : new String[] {"url", "user", "password",
                    "authentication, dmi-service-name"}) {
                config.put(param, properties.getProperty(param));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        LOG.info("addCMHandle Session Initiated");
    }

    @Override
    public void onCreated(NodeId nNodeId, NetconfNode netconfNode) {
        LOG.info("NetConf device connected ", nNodeId.getValue());
        JSONObject obj = new JSONObject();
        obj.put("cm-handle-id", nNodeId.getValue());
        obj.put("dmi-service-name", config.get("dmi-service-name"));
        ClientConfig dmaapClientConfig = new DefaultClientConfig();
        dmaapClientConfig.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, 180000);
        dmaapClientConfig.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, 60000);
        Client dmaapClient = Client.create(dmaapClientConfig);
        String authenticationMethod = config.get("authentication");
        ClientResponse response = null;
        try {
            if (authenticationMethod.equals("basic")) {
                LOG.debug("Sending message to dmaap-message-router: {}", obj.toString());
                dmaapClient.addFilter(new HTTPBasicAuthFilter(config.get("user"), config.get("password")));

                response = dmaapClient.resource(config.get("url")).type(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, obj);
            } else {
                response = dmaapClient.resource(config.get("url")).type(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, obj);
            }
        } catch (Exception e) {
            LOG.error("Error while posting message to CM_HANDLE topic: {}", e);
        }

        LOG.info("Received response from dmaap-message-router: \n {}", response.toString());
    }

    @Override
    public void onRemoved(NodeId nNodeId) {

        LOG.info("NetConf device removed - nNodeId = {}", nNodeId);
    }

    @Override
    public void onStateChange(NodeId nNodeId, NetconfNode netconfNode) {
        LOG.info("NetConf device state changed nNodeId = {}}", nNodeId);
    }

    /**
     * Method called when the blueprint container is destroyed.
     */
    public void close() {
        rpcRegistration.close();
        LOG.debug("AddCMHandleProvider Closed");
    }

    @Override
    public ListenableFuture<RpcResult<AddCMHandleOutput>> addCMHandle(AddCMHandleInput input) {

        return null;
    }
}