2 package evel_javalibrary.att.com;
4 /**************************************************************************//**
6 * Header for EVEL library
8 * This file implements the EVEL library which is intended to provide a
9 * simple wrapper around the complexity of AT&T's Vendor Event Listener API so
10 * that VNFs can use it without worrying about details of the API transport.
14 * Unless otherwise specified, all software contained herein is
15 * Licensed under the Apache License, Version 2.0 (the "License");
16 * you may not use this file except in compliance with the License.
17 * You may obtain a copy of the License at
18 * http://www.apache.org/licenses/LICENSE-2.0
20 * Unless required by applicable law or agreed to in writing, software
21 * distributed under the License is distributed on an "AS IS" BASIS,
22 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23 * See the License for the specific language governing permissions and
24 * limitations under the License.
25 *****************************************************************************/
27 import org.apache.log4j.Logger;
28 import org.apache.log4j.Level;
30 import java.io.BufferedReader;
31 import java.io.BufferedWriter;
32 //import java.io.DataOutputStream;
33 import java.io.IOException;
34 import java.io.InputStream;
35 //import java.io.InputStreamReader;
36 import java.io.OutputStream;
37 import java.io.OutputStreamWriter;
38 import java.net.HttpURLConnection;
39 import java.net.MalformedURLException;
40 //import java.net.ProtocolException;
42 //import java.nio.charset.StandardCharsets;
45 import javax.net.ssl.HttpsURLConnection;
47 import org.apache.log4j.BasicConfigurator;
50 * @author Gokul Singaraju
54 public class AgentMain {
56 /**************************************************************************//**
59 * Error codes for EVEL low level interface
60 *****************************************************************************/
61 public enum EVEL_ERR_CODES {
62 EVEL_SUCCESS, /** The operation was successful. */
63 EVEL_ERR_GEN_FAIL, /** Non-specific failure. */
64 EVEL_CURL_LIBRARY_FAIL, /** A cURL library operation failed. */
65 EVEL_PTHREAD_LIBRARY_FAIL, /** A Posix threads operation failed. */
66 EVEL_OUT_OF_MEMORY, /** A memory allocation failure occurred. */
67 EVEL_EVENT_BUFFER_FULL, /** Too many events in the ring-buffer. */
68 EVEL_EVENT_HANDLER_INACTIVE, /** Attempt to raise event when inactive. */
69 EVEL_NO_METADATA, /** Failed to retrieve OpenStack metadata. */
70 EVEL_BAD_METADATA, /** OpenStack metadata invalid format. */
71 EVEL_BAD_JSON_FORMAT, /** JSON failed to parse correctly. */
72 EVEL_JSON_KEY_NOT_FOUND, /** Failed to find the specified JSON key. */
73 EVEL_MAX_ERROR_CODES /** Maximum number of valid error codes. */
76 private static final Logger logger = Logger.getLogger(AgentMain.class);
78 private static String url = null;
79 private static URL vesurl = null;
80 private static HttpURLConnection con = null;
81 private static String userpass = null;
82 private static String version = "5";
84 /* RingBuffer to forward messages on sending AgentDispatcher thread */
85 private static RingBuffer ringb = new RingBuffer(100);
89 /* AgentDispatcher loops on messages in RingBuffer and POSTs them
90 * to external Collector
92 private static class AgentDispatcher implements Runnable {
94 private String readStream(InputStream stream) throws Exception {
95 StringBuilder builder = new StringBuilder();
96 try (BufferedReader in = new BufferedReader(new InputStreamReader(stream))) {
98 while ((line = in.readLine()) != null) {
99 builder.append(line); // + "\r\n"(no need, json has no line breaks!)
103 logger.error("Resp: " + builder.toString());
104 System.out.println("Resp: " + builder.toString());
105 return builder.toString();
110 String datatosend=null;
112 if( (datatosend = (String) ringb.take()) != null )
116 logger.trace(url + "Got an event size "+datatosend.length());
117 logger.trace(datatosend);
121 //HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
122 con = (HttpURLConnection) vesurl.openConnection();
123 if (con instanceof HttpsURLConnection) {
124 HttpsURLConnection httpsConnection = (HttpsURLConnection) con;
125 //SSLContext sc = SSLContext.getInstance("TLSv1.2");
126 // Init the SSLContext with a TrustManager[] and SecureRandom()
127 //sc.init(null, null, new java.security.SecureRandom());
128 //httpsConnection.setHostnameVerifier(getHostnameVerifier());
129 //httpsConnection.setSSLSocketFactory(sc.getSocketFactory());
130 con = httpsConnection;
134 con.setRequestMethod("POST");
135 //con.setRequestProperty("User-Agent", USER_AGENT);
136 //con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
137 // No caching, we want the real thing.
138 con.setUseCaches (false);
139 // Specify the content type.
140 con.setRequestProperty("Content-Type", "application/json");
141 //con.setChunkedStreamingMode(0);
142 con.setInstanceFollowRedirects( false );
143 //Basic username password authentication
144 String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8"));
145 con.setRequestProperty ("Authorization", basicAuth);
147 con.setReadTimeout(15000 /* milliseconds */);
148 con.setConnectTimeout(15000 /* milliseconds */);
150 con.setDoOutput(true);
151 con.setDoInput(true);
153 con.setFixedLengthStreamingMode(datatosend.length());
154 OutputStream os = con.getOutputStream();
155 BufferedWriter writer = new BufferedWriter(
156 new OutputStreamWriter(os, "UTF-8"));
158 writer.write(datatosend);
162 //Handle the response code for POST request
163 int respCode = con.getResponseCode();
164 logger.trace(url + "Connection HTTP Response code :"+respCode);
165 if(respCode < HttpURLConnection.HTTP_OK ) {
166 logger.trace(url + " **INFO**");
168 else if(respCode >= HttpURLConnection.HTTP_OK && respCode < HttpURLConnection.HTTP_MULT_CHOICE )
170 logger.trace(url + " **OK**");
172 else if(respCode >= HttpURLConnection.HTTP_MULT_CHOICE && respCode < HttpURLConnection.HTTP_BAD_REQUEST )
174 logger.warn(url + " **REDIRECTION**");
176 else if(respCode >= HttpURLConnection.HTTP_BAD_REQUEST )
178 logger.warn(url + " **SERVER ERROR**");
180 InputStream es = con.getErrorStream();
185 } catch (IOException e) {
186 // TODO Auto-generated catch block
188 } catch (Exception e) {
189 // TODO Auto-generated catch block
196 logger.trace(url + "Waiting for events");
199 } catch (InterruptedException e) {
200 // TODO Auto-generated catch block
206 }//end AgentDispatcher
208 public static boolean isValidURL(String urlStr) {
210 URL url = new URL(urlStr);
213 catch (MalformedURLException e) {
218 /**************************************************************************//**
219 * Library initialization.
221 * Initialize the EVEL library.
223 * @note This function initializes the Java EVEL library interfaces.
224 * Validates input parameters and starts the AgentDispatcher thread
226 * @param event_api_url The API's URL.
227 * @param port The API's port.
228 * @param path The optional path (may be NULL).
229 * @param topic The optional topic part of the URL (may be NULL).
230 * @param username Username for Basic Authentication of requests.
231 * @param password Password for Basic Authentication of requests.
232 * @param Level Java Log levels.
234 * @returns Status code
235 * @retval EVEL_SUCCESS On success
236 * @retval ::EVEL_ERR_CODES On failure.
237 *****************************************************************************/
238 public static EVEL_ERR_CODES evel_initialize(
239 String event_api_url,
245 Level level) throws IOException
247 EVEL_ERR_CODES rc = EVEL_ERR_CODES.EVEL_SUCCESS;
248 String throt_api_url = "http://127.0.0.1";
252 BasicConfigurator.configure();
254 /***************************************************************************/
255 /* Check assumptions. */
256 /***************************************************************************/
257 assert(event_api_url != null);
259 assert(throt_api_url != null);
260 assert(username != null);
262 logger.setLevel(level);
264 if( !isValidURL(event_api_url) || !isValidURL(throt_api_url)){
265 System.out.println("Invalid Event API URL");
266 rc = EVEL_ERR_CODES.EVEL_ERR_GEN_FAIL;
273 version += "/example_vnf";
276 url = event_api_url+":"+Integer.toString(port)+path+"/eventListener/v"+version;
279 vesurl = new URL(url);
280 } catch (MalformedURLException e) {
281 // TODO Auto-generated catch block
282 logger.info("Error in url input");
286 userpass = username + ":" + password;
288 logger.info("Starting Agent Dispatcher thread");
289 long startTime = System.currentTimeMillis();
290 Thread t = new Thread(new AgentDispatcher());
298 private static void EVEL_EXIT() {
299 // TODO Auto-generated method stub
303 private static void EVEL_ENTER() {
304 // TODO Auto-generated method stub
308 /**************************************************************************//**
309 * Handle user formatted post message
311 * @note This function handles VES 5.x formatted messages from all valid
312 * Domains and stores them in RingBuffer.
314 * @param obj VES 5.x formatted user messages with common header
315 * and optional specialized body
317 * @retval boolean True On successful acceptance False on failure
318 *****************************************************************************/
320 public static boolean evel_post_event(EvelHeader obj )
322 String data = obj.evel_json_encode_event();
323 boolean ret = ringb.put(data);
324 logger.info("Evel Post event ret:"+ret);