2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.features.sdnr.northbound.energysavings;
24 import java.io.FileInputStream;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.Properties;
30 import java.util.concurrent.Future;
31 import javax.ws.rs.HttpMethod;
32 import javax.ws.rs.core.MediaType;
33 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.energysavings.rev150105.EnergysavingsService;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.energysavings.rev150105.PayloadInput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.energysavings.rev150105.PayloadInputBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.energysavings.rev150105.PayloadOutput;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.energysavings.rev150105.PayloadOutputBuilder;
39 import org.opendaylight.yangtools.yang.common.RpcResult;
40 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
44 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
45 import com.google.common.base.Preconditions;
46 import com.google.common.util.concurrent.Futures;
47 import com.sun.jersey.api.client.Client;
48 import com.sun.jersey.api.client.ClientResponse;
49 import com.sun.jersey.api.client.WebResource;
50 import com.sun.jersey.api.client.config.ClientConfig;
51 import com.sun.jersey.api.client.config.DefaultClientConfig;
52 import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
54 public class EnergysavingsProvider implements EnergysavingsService {
56 private static final Logger LOG = LoggerFactory.getLogger(EnergysavingsProvider.class);
58 private final String appName = "EnergySavings";
60 private final DataBroker dataBroker;
61 private final RpcProviderRegistry rpcProviderRegistry;
62 private RpcRegistration<EnergysavingsService> serviceRegistration;
64 // Locations and names of the configuration files
65 private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR";
66 private static final String PROPERTIES_FILE_NAME = "sdnr-energy-savings.properties";
67 private static final String PARSING_ERROR =
68 "Could not create the request message to send to the server; no message will be sent";
71 * Use a flag veryFirstTime to ensure that some tasks are done only once. The value is set here and
72 * during initialization.
74 private Boolean veryFirstTime = true;
76 // Parameters for the REST calls
78 // to publish SDNR_TO_POLICY DMaaP topic
79 private WebResource dmaapSdnrToPolicyWebResource = null;
81 // to the Energy Savings server
82 private WebResource energySavingsWebResource = null;
84 public EnergysavingsProvider(final DataBroker dataBroker, RpcProviderRegistry rpcProviderRegistry) {
85 this.dataBroker = dataBroker;
86 this.rpcProviderRegistry = rpcProviderRegistry;
90 * Method called when the blueprint container is created.
93 serviceRegistration = rpcProviderRegistry.addRpcImplementation(EnergysavingsService.class, this);
95 LOG.debug("Initializing provider for " + appName);
97 Preconditions.checkNotNull(dataBroker, "dataBroker must be set");
99 // Set the initialization flag so some tasks will be done only once
100 veryFirstTime = true;
102 // Read parameters from the properties file in SDNC_CONFIG_DIR
103 String propDir = System.getenv(SDNC_CONFIG_DIR);
104 if (propDir == null) {
105 LOG.error("Environment variable SDNC_CONFIG_DIR is not set");
106 propDir = "/opt/onap/ccsdk/data/properties/";
107 } else if (!propDir.endsWith("/")) {
108 propDir = propDir + "/";
111 // Get the parameters for the REST calls
112 HashMap<String, String> dmaapPolicyHttpParams = new HashMap<String, String>();
113 HashMap<String, String> energySavingsServerHttpParams = new HashMap<String, String>();
116 FileInputStream fileInput = new FileInputStream(propDir + PROPERTIES_FILE_NAME);
117 Properties properties = new Properties();
118 properties.load(fileInput);
121 for (String param : new String[] {"url", "httpMethod", "authentication", "user", "password"}) {
122 dmaapPolicyHttpParams.put(param, properties.getProperty("dmaapPolicy." + param));
123 energySavingsServerHttpParams.put(param, properties.getProperty("energySavingsServer." + param));
125 } catch (FileNotFoundException e) {
127 } catch (IOException e) {
131 // Create a web resource for the Energy Savings server
132 ClientConfig esClientConfig = new DefaultClientConfig();
133 // 3 minute read time out
134 esClientConfig.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, 180000);
135 // 1 minute connect time out
136 esClientConfig.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, 60000);
137 Client esClient = Client.create(esClientConfig);
139 // Authentication for the Energy Savings server
140 String authenticationMethod = energySavingsServerHttpParams.get("authentication");
142 if (authenticationMethod.equals("basic")) {
143 esClient.addFilter(new HTTPBasicAuthFilter(energySavingsServerHttpParams.get("user"),
144 energySavingsServerHttpParams.get("password")));
145 energySavingsWebResource = esClient.resource(energySavingsServerHttpParams.get("url"));
146 } else if (authenticationMethod.equals("none")) {
147 energySavingsWebResource = esClient.resource(energySavingsServerHttpParams.get("url"));
149 LOG.error("Unexpected value for energy savings server authentication: " + authenticationMethod);
152 // Create a web resource for the DMaaP SDNR_TO_POLICY topic
153 ClientConfig dmaapClientConfig = new DefaultClientConfig();
154 // 3 minute read time out
155 dmaapClientConfig.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, 180000);
156 // 1 minute connect time out
157 dmaapClientConfig.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, 60000);
158 Client dmaapClient = Client.create(dmaapClientConfig);
160 // Authentication for the DMaaP message router
161 authenticationMethod = dmaapPolicyHttpParams.get("authentication");
163 if (authenticationMethod.equals("basic")) {
164 dmaapClient.addFilter(
165 new HTTPBasicAuthFilter(dmaapPolicyHttpParams.get("user"), dmaapPolicyHttpParams.get("password")));
166 dmaapSdnrToPolicyWebResource = dmaapClient.resource(dmaapPolicyHttpParams.get("url"));
167 } else if (authenticationMethod.equals("none")) {
168 dmaapSdnrToPolicyWebResource = dmaapClient.resource(dmaapPolicyHttpParams.get("url"));
170 LOG.error("Unexpected value for DMaaP message router authentication: " + authenticationMethod);
173 LOG.debug("energySavingsServerHttpParams: " + Collections.singletonList(energySavingsServerHttpParams));
174 LOG.debug("dmaapPolicyHttpParams: " + Collections.singletonList(dmaapPolicyHttpParams));
175 LOG.debug("Initialization complete for " + appName);
179 * Method called when the blueprint container is destroyed.
181 public void close() {
182 LOG.debug("EnergysavingsProvider Closed");
185 public WebResource getDmaapSdnrToPolicyWebResource() {
186 return this.dmaapSdnrToPolicyWebResource;
189 public WebResource getEnergySavingsWebResource() {
190 return this.energySavingsWebResource;
194 public Future<RpcResult<PayloadOutput>> payload(PayloadInput input) {
197 * Policy has published a POLICY_TO_SDNR DMaaP topic. Currently, this feature simply forwards the
198 * input to the Energy Savings server untouched.
202 Boolean requestSucceeded = true;
204 // Build the result now so error messages can be included in the response
205 PayloadOutputBuilder resultBuilder = new PayloadOutputBuilder();
208 LOG.error("Input is null");
209 resultBuilder.setResult("Input is null");
210 requestSucceeded = false;
213 PayloadInputBuilder inputBuilder = new PayloadInputBuilder(input);
214 input = inputBuilder.build();
215 LOG.debug("Received payload: " + input.getPayload());
216 } catch (Exception e) {
217 LOG.error("Cannot build input");
218 resultBuilder.setResult(e.toString() + " : " + e.getMessage());
219 requestSucceeded = false;
224 * See if the web resources were created during initialization. No use in proceeding if not.
226 if (energySavingsWebResource == null) {
227 LOG.error("energySavingsWebResouce is null");
228 resultBuilder.setResult("energySavingsWebResource is null");
229 requestSucceeded = false;
232 if (dmaapSdnrToPolicyWebResource == null) {
233 LOG.error("dmaapSdnrToPolicyWebResouce is null");
234 resultBuilder.setResult("dmaapSdnrToPolicyWebResource is null");
235 requestSucceeded = false;
239 * Forward the POLICY_TO_SDNR message to the Energy Savings server
242 ClientResponse response = null;
243 if (requestSucceeded) {
245 LOG.debug("Sending message to controller: \n" + input.getPayload());
246 response = energySavingsWebResource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
247 .method(HttpMethod.POST, ClientResponse.class, input.getPayload());
248 LOG.debug("Received response from Energy Savings server: \n" + response.toString());
249 } catch (Exception e) {
250 LOG.error("Error while posting POLICY_TO_SDNR input to server:", e);
251 resultBuilder.setResult("Error while posting POLICY_TO_SDNR input to server\n" + e.toString());
252 requestSucceeded = false;
257 * Return the response from the server to Policy using the SDNR_TO_POLICY topic
260 if (requestSucceeded) {
261 String esServerResponse = response.getEntity(String.class);
263 LOG.debug("Sending SDNR_TO_POLICY topic: \n" + esServerResponse);
265 dmaapSdnrToPolicyWebResource.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)
266 .method(HttpMethod.POST, ClientResponse.class, esServerResponse);
267 LOG.debug("Received response from DMaaP message router: \n" + response.toString());
268 } catch (Exception e) {
269 LOG.error("Error while posting SDNR_TO_POLICY topic: ", e);
270 resultBuilder.setResult("Error while posting SDNR_TO_POLICY topic:\n" + e.toString());
271 requestSucceeded = false;
275 if (requestSucceeded) {
276 return Futures.immediateFuture(
277 RpcResultBuilder.<PayloadOutput>success().withResult(resultBuilder.build()).build());
279 return Futures.immediateFuture(
280 RpcResultBuilder.<PayloadOutput>failed().withResult(resultBuilder.build()).build());