Feature for micro service communication
[appc.git] / appc-service-communicator / appc-service-communicator-bundle / src / main / java / org / onap / appc / srvcomm / messaging / MessagingConnector.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.appc.srvcomm.messaging;
23
24 import java.io.IOException;
25 import java.io.UnsupportedEncodingException;
26 import java.util.Properties;
27
28 import org.apache.commons.codec.binary.Base64;
29 import org.apache.http.client.ClientProtocolException;
30 import org.apache.http.client.methods.CloseableHttpResponse;
31 import org.apache.http.client.methods.HttpPost;
32 import org.apache.http.entity.StringEntity;
33 import org.apache.http.impl.client.CloseableHttpClient;
34 import org.apache.http.impl.client.HttpClientBuilder;
35 import org.onap.appc.configuration.ConfigurationFactory;
36
37 import com.att.eelf.configuration.EELFLogger;
38 import com.att.eelf.configuration.EELFManager;
39
40 public class MessagingConnector {
41
42     private static final EELFLogger LOG = EELFManager.getInstance().getLogger(MessagingConnector.class);
43
44     private final String URL;
45     private final String USER;
46     private final String PASSWORD;
47     private final String PROPERTIES_PREFIX = "appc.srvcomm.messaging";
48
49     public MessagingConnector() {
50         Properties props = ConfigurationFactory.getConfiguration().getProperties();
51         String url = props.getProperty(PROPERTIES_PREFIX + ".url");
52         if(!isNullOrEmpty(url)) {
53             this.URL = url;
54         } else {
55             this.URL = "localhost:8080";
56         }
57         String username = props.getProperty(PROPERTIES_PREFIX + ".username");
58         String password = props.getProperty(PROPERTIES_PREFIX + ".password");
59         //Both username and password properties need to be set. One or the other
60         //can't be set.
61         if(isNullOrEmpty(username, password)) {
62             USER = null;
63             PASSWORD = null;
64         } else {
65             USER = username;
66             PASSWORD = password;
67         }
68     }
69
70     public boolean isNullOrEmpty(String... strings) {
71         for(String s : strings) {
72             if(s == null || s.isEmpty()){
73                 return true;
74             }
75         }
76         return false;
77     }
78
79     public boolean publishMessage(String propertySet, String partition, String data) {
80         return publishMessage(propertySet, partition, null, data);
81     }
82
83     public boolean publishMessage(String propertySet, String partition, String topic, String data) {
84         HttpPost post = new HttpPost(URL);
85         //check if we need to enable authentication
86         if(USER != null) {
87             String authStr = getBasicAuth(USER, PASSWORD);
88             post.setHeader("Authorization", String.format("Basic %s", authStr));
89         }
90         //encode the message so it can be sent to the dmaap client jar
91         String body = bodyLine(propertySet, partition, topic, data);
92         try {
93             post.setEntity(new StringEntity(body));
94         } catch (UnsupportedEncodingException e) {
95             LOG.error("Error during publishMessage",e);
96         }
97         try {
98             CloseableHttpResponse response = getClient().execute(post);
99             if (response.getStatusLine().getStatusCode() == 200) {
100                 return true;
101             } else {
102                 LOG.error(response.getStatusLine().getStatusCode() +
103                         " Error during publishMessage: " +
104                         response.getStatusLine().getReasonPhrase() +
105                         " See messaging service jar logs.");
106                 return false;
107             }
108         } catch (ClientProtocolException e) {
109             LOG.error("Error during publishMessage",e);
110         } catch (IOException e) {
111             LOG.error("Error during publishMessage",e);
112         }
113         return false;
114
115     }
116
117     /**
118      * Format the body for the application/cambria content type with no partitioning. See
119      *
120      * @param propertySet
121      *            The prefix of the properties that the dmaap service should look up in order to
122      *            get the correct properties for the message being sent.
123      * @param partition
124      *            The dmaap partition that the message should be published to
125      * @param topic
126      *            The dmaap topic that the message should be published to. Leave this unset in order
127      *            to use the topic that is in the property files.
128      * @param message
129      *            The message to publish
130      * @return A string in the application/cambria content type
131      */
132     private String bodyLine(String propertySet, String partition, String topic, String message) {
133         String prop = (propertySet == null) ? "" : propertySet;
134         String prt = (partition == null) ? "" : partition;
135         String msg = (message == null) ? "" : message;
136         String top = (topic == null) ? "" : topic;
137         return String.format("%d.%d.%d.%d.%s%s%s%s", prop.length(),prt.length(), top.length(),
138                 msg.length(), prop, prt, top, msg);
139     }
140
141     protected CloseableHttpClient getClient() {
142         return HttpClientBuilder.create().build();
143     }
144
145     protected String getBasicAuth(String username, String password) {
146         if (username != null && password != null) {
147             String plain = String.format("%s:%s", username, password);
148             return Base64.encodeBase64String(plain.getBytes());
149         } else {
150             return null;
151         }
152     }
153
154 }