Merge of new rebased code
[appc.git] / appc-oam / appc-oam-bundle / src / main / java / org / openecomp / appc / oam / messageadapter / MessageAdapter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
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
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
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=========================================================
20  */
21
22 package org.openecomp.appc.oam.messageadapter;
23
24 import org.openecomp.appc.adapter.message.MessageAdapterFactory;
25 import org.openecomp.appc.adapter.message.Producer;
26 import org.openecomp.appc.configuration.Configuration;
27 import org.openecomp.appc.configuration.ConfigurationFactory;
28 import org.openecomp.appc.listener.impl.EventHandlerImpl;
29 import org.osgi.framework.BundleContext;
30 import org.osgi.framework.FrameworkUtil;
31 import org.osgi.framework.ServiceReference;
32
33 import com.att.eelf.configuration.EELFLogger;
34 import com.att.eelf.configuration.EELFManager;
35 import com.fasterxml.jackson.core.JsonProcessingException;
36 import org.apache.commons.lang.ObjectUtils;
37
38 import java.util.HashSet;
39 import java.util.Properties;
40
41 public class MessageAdapter {
42
43     private Producer producer;
44     private String partition ;
45     private Configuration configuration;
46     private HashSet<String> pool;
47     private String writeTopic;
48     private String apiKey;
49     private String apiSecret;
50
51     private static final EELFLogger logger = EELFManager.getInstance().getLogger(MessageAdapter.class);
52
53     /**
54      * Initialize producer client to post messages using configuration properties
55      */
56     public void init(){
57         this.producer = getProducer();
58     }
59
60     private Producer getProducer() {
61         configuration = ConfigurationFactory.getConfiguration();
62         Properties properties=configuration.getProperties();
63         updateProperties(properties);
64         Producer localProducer = null;
65         
66         BundleContext ctx = FrameworkUtil.getBundle(EventHandlerImpl.class).getBundleContext();
67         if (ctx != null) {
68                 ServiceReference svcRef = ctx.getServiceReference(MessageAdapterFactory.class.getName());
69                 if (svcRef != null) {
70                         localProducer = ((MessageAdapterFactory) ctx.getService(svcRef)).createProducer(pool, writeTopic, apiKey, apiSecret);
71                         for (String url : pool) {
72                             if (url.contains("3905") || url.contains("https")) {
73                                 localProducer.useHttps(true);
74                                 break;
75                             }
76                         }
77                 }
78         }
79
80         return localProducer;
81     }
82
83     private void updateProperties(Properties props) {
84         if (logger.isTraceEnabled()) {
85             logger.trace("Entering to updateProperties with Properties = "+ ObjectUtils.toString(props));
86         }
87         pool = new HashSet<>();
88         if (props != null) {
89             writeTopic = props.getProperty("appc.OAM.topic.write");
90             apiKey = props.getProperty("appc.OAM.client.key");
91             apiSecret = props.getProperty("appc.OAM.client.secret");
92             String hostnames = props.getProperty("appc.OAM.poolMembers");
93             if (hostnames != null && !hostnames.isEmpty()) {
94                 for (String name : hostnames.split(",")) {
95                     pool.add(name);
96                 }
97             }
98         }
99     }
100
101     /**
102      * Posts message to UEB. As UEB accepts only json messages this method first convert uebMessage to json format and post it to UEB.
103      * @param oamContext response data that based on it a message will be send to UEB (the format of the message that will be sent to UEB based on the action and its YANG domainmodel).
104      * @return True if message is postes successfully else False
105      */
106     public boolean post(OAMContext oamContext){
107         boolean success;
108         if (logger.isTraceEnabled()) {
109             logger.trace("Entering to post with AsyncResponse = " + ObjectUtils.toString(oamContext));
110         }
111
112         String jsonMessage;
113         try {
114             jsonMessage = Converter.convAsyncResponseToUebOutgoingMessageJsonString(oamContext);
115             if (logger.isDebugEnabled()) {
116                 logger.debug("UEB Response = " + jsonMessage);
117             }
118             success  = producer.post(this.partition, jsonMessage);
119         } catch (JsonProcessingException e1) {
120             logger.error("Error generating Jason from UEB message "+ e1.getMessage());
121             success= false;
122         }catch (Exception e){
123             logger.error("Error sending message to UEB "+e.getMessage());
124             success= false;
125         }
126         if (logger.isTraceEnabled()) {
127             logger.trace("Exiting from post with (success = "+ ObjectUtils.toString(success)+")");
128         }
129         return success;
130     }
131 }