Add junit coverage to RequestInfoBuilder class
[appc.git] / appc-oam / appc-oam-bundle / src / main / java / org / onap / appc / oam / messageadapter / MessageAdapter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.oam.messageadapter;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.fasterxml.jackson.core.JsonProcessingException;
30 import org.apache.commons.lang.ObjectUtils;
31 import org.onap.appc.adapter.message.MessageAdapterFactory;
32 import org.onap.appc.adapter.message.Producer;
33 import org.onap.appc.configuration.Configuration;
34 import org.onap.appc.configuration.ConfigurationFactory;
35 import org.osgi.framework.BundleContext;
36 import org.osgi.framework.FrameworkUtil;
37 import org.osgi.framework.ServiceReference;
38
39 import java.util.HashSet;
40 import java.util.Properties;
41
42 public class MessageAdapter {
43
44     private final EELFLogger logger = EELFManager.getInstance().getLogger(MessageAdapter.class);
45
46     private final String PROP_APPC_OAM_DISABLED = "appc.OAM.disabled";
47     private final String PROP_APPC_OAM_TOPIC_WRITE = "appc.OAM.topic.write";
48     private String PROP_APPC_OAM_CLIENT_KEY = "appc.OAM.client.key";
49     private String PROP_APPC_OAM_CLIENT_SECRET = "appc.OAM.client.secret";
50     private String PROP_APPC_OAM_POOLMEMBERS = "appc.OAM.poolMembers";
51
52     private Producer producer;
53     private String partition;
54     private Configuration configuration;
55     private HashSet<String> pool;
56     private String writeTopic;
57     private String apiKey;
58     private String apiSecret;
59     private boolean isDisabled;
60
61     /**
62      * Initialize producer client to post messages using configuration properties.
63      */
64     public void init() {
65         configuration = ConfigurationFactory.getConfiguration();
66         Properties properties = configuration.getProperties();
67         updateProperties(properties);
68
69         if (isAppcOamPropsListenerEnabled()) {
70             createProducer();
71         } else {
72             logger.warn(String.format("The listener %s is disabled and will not be run", "appc.OAM"));
73         }
74     }
75
76     /**
77      * Create producer using MessageAdapterFactory which is found through bundle context.
78      */
79     void createProducer() {
80         BundleContext ctx = FrameworkUtil.getBundle(MessageAdapter.class).getBundleContext();
81         if (ctx == null) {
82             logger.warn("MessageAdapter cannot create producer due to no bundle context.");
83             return;
84         }
85
86         ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName());
87         if (svcRef == null) {
88             logger.warn("MessageAdapter cannot create producer due to no MessageAdapterFactory service reference.");
89             return;
90         }
91
92         Producer localProducer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic,
93                 apiKey, apiSecret);
94
95         for (String url : pool) {
96             if (url.contains("3905") || url.contains("https")) {
97                 localProducer.useHttps(true);
98                 break;
99             }
100         }
101
102         producer = localProducer;
103
104         logger.debug("MessageAdapter created producer.");
105     }
106
107     /**
108      * Read property value to set writeTopic, apiKey, apiSecret and pool.
109      *
110      * @param props of configuration
111      */
112     private void updateProperties(Properties props) {
113         logger.trace("Entering to updateProperties with Properties = " + ObjectUtils.toString(props));
114
115         pool = new HashSet<>();
116         if (props != null) {
117             isDisabled = Boolean.parseBoolean(props.getProperty(PROP_APPC_OAM_DISABLED));
118             writeTopic = props.getProperty(PROP_APPC_OAM_TOPIC_WRITE);
119             apiKey = props.getProperty(PROP_APPC_OAM_CLIENT_KEY);
120             apiSecret = props.getProperty(PROP_APPC_OAM_CLIENT_SECRET);
121             String hostnames = props.getProperty(PROP_APPC_OAM_POOLMEMBERS);
122             if (hostnames != null && !hostnames.isEmpty()) {
123                 for (String name : hostnames.split(",")) {
124                     pool.add(name);
125                 }
126             }
127         }
128     }
129
130     /**
131      * Get producer. If it is null, call createProducer to create it again.
132      *
133      * @return Producer
134      */
135     Producer getProducer() {
136         if (producer == null) {
137             // In case, producer was not properly set yet, set it again.
138             logger.info("Calling createProducer as producer is null.");
139             createProducer();
140         }
141
142         return producer;
143     }
144
145     /**
146      * Posts message to UEB. As UEB accepts only json messages this method first convert uebMessage to json format
147      * and post it to UEB.
148      *
149      * @param oamContext response data that based on it a message will be send to UEB (the format of the message that
150      *                   will be sent to UEB based on the action and its YANG domainmodel).
151      */
152     public void post(OAMContext oamContext) {
153         if (logger.isTraceEnabled()) {
154             logger.trace("Entering to post with AsyncResponse = " + ObjectUtils.toString(oamContext));
155         }
156
157         boolean success;
158         String jsonMessage;
159         try {
160             jsonMessage = Converter.convAsyncResponseToUebOutgoingMessageJsonString(oamContext);
161             if (logger.isDebugEnabled()) {
162                 logger.debug("UEB Response = " + jsonMessage);
163             }
164
165             Producer myProducer = getProducer();
166             success = myProducer != null && myProducer.post(this.partition, jsonMessage);
167         } catch (JsonProcessingException e1) {
168             logger.error("Error generating Json from UEB message " + e1.getMessage());
169             success = false;
170         } catch (Exception e) {
171             logger.error("Error sending message to UEB " + e.getMessage(), e);
172             success = false;
173         }
174
175         if (logger.isTraceEnabled()) {
176             logger.trace("Exiting from post with (success = " + ObjectUtils.toString(success) + ")");
177         }
178     }
179
180     private boolean isAppcOamPropsListenerEnabled() {
181         return !isDisabled;
182     }
183 }