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 {
95 String datatosend=null;
97 if( (datatosend = (String) ringb.take()) != null )
101 logger.trace(url + "Got an event size "+datatosend.length());
102 logger.trace(datatosend);
106 //HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
107 con = (HttpURLConnection) vesurl.openConnection();
108 if (con instanceof HttpsURLConnection) {
109 HttpsURLConnection httpsConnection = (HttpsURLConnection) con;
110 //SSLContext sc = SSLContext.getInstance("TLSv1.2");
111 // Init the SSLContext with a TrustManager[] and SecureRandom()
112 //sc.init(null, null, new java.security.SecureRandom());
113 //httpsConnection.setHostnameVerifier(getHostnameVerifier());
114 //httpsConnection.setSSLSocketFactory(sc.getSocketFactory());
115 con = httpsConnection;
119 con.setRequestMethod("POST");
120 //con.setRequestProperty("User-Agent", USER_AGENT);
121 //con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
122 // No caching, we want the real thing.
123 con.setUseCaches (false);
124 // Specify the content type.
125 con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
126 //con.setChunkedStreamingMode(0);
127 con.setInstanceFollowRedirects( false );
128 //Basic username password authentication
129 String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8"));
130 con.setRequestProperty ("Authorization", basicAuth);
132 con.setReadTimeout(15000 /* milliseconds */);
133 con.setConnectTimeout(15000 /* milliseconds */);
135 con.setDoOutput(true);
136 con.setDoInput(true);
138 con.setFixedLengthStreamingMode(datatosend.length());
139 OutputStream os = con.getOutputStream();
140 BufferedWriter writer = new BufferedWriter(
141 new OutputStreamWriter(os, "UTF-8"));
143 writer.write(datatosend);
147 //Handle the response code for POST request
148 int respCode = con.getResponseCode();
149 logger.trace(url + "Connection HTTP Response code :"+respCode);
150 if(respCode < HttpURLConnection.HTTP_OK ) {
151 logger.trace(url + " **INFO**");
153 else if(respCode >= HttpURLConnection.HTTP_OK && respCode < HttpURLConnection.HTTP_MULT_CHOICE )
155 logger.trace(url + " **OK**");
157 else if(respCode >= HttpURLConnection.HTTP_MULT_CHOICE && respCode < HttpURLConnection.HTTP_BAD_REQUEST )
159 logger.warn(url + " **REDIRECTION**");
161 else if(respCode >= HttpURLConnection.HTTP_BAD_REQUEST )
163 logger.warn(url + " **SERVER ERROR**");
165 InputStream es = con.getErrorStream();
170 // read the response body
171 while ((ret = es.read(buf)) > 0) {
172 logger.info("Resp:"+buf);
174 // close the errorstream
180 } catch (IOException e) {
181 // TODO Auto-generated catch block
188 logger.trace(url + "Waiting for events");
191 } catch (InterruptedException e) {
192 // TODO Auto-generated catch block
198 }//end AgentDispatcher
200 public static boolean isValidURL(String urlStr) {
202 URL url = new URL(urlStr);
205 catch (MalformedURLException e) {
210 /**************************************************************************//**
211 * Library initialization.
213 * Initialize the EVEL library.
215 * @note This function initializes the Java EVEL library interfaces.
216 * Validates input parameters and starts the AgentDispatcher thread
218 * @param event_api_url The API's URL.
219 * @param port The API's port.
220 * @param path The optional path (may be NULL).
221 * @param topic The optional topic part of the URL (may be NULL).
222 * @param username Username for Basic Authentication of requests.
223 * @param password Password for Basic Authentication of requests.
224 * @param Level Java Log levels.
226 * @returns Status code
227 * @retval EVEL_SUCCESS On success
228 * @retval ::EVEL_ERR_CODES On failure.
229 *****************************************************************************/
230 public static EVEL_ERR_CODES evel_initialize(
231 String event_api_url,
237 Level level) throws IOException
239 EVEL_ERR_CODES rc = EVEL_ERR_CODES.EVEL_SUCCESS;
240 String throt_api_url = "http://127.0.0.1";
244 BasicConfigurator.configure();
246 /***************************************************************************/
247 /* Check assumptions. */
248 /***************************************************************************/
249 assert(event_api_url != null);
251 assert(throt_api_url != null);
252 assert(username != null);
254 logger.setLevel(level);
256 if( !isValidURL(event_api_url) || !isValidURL(throt_api_url)){
257 System.out.println("Invalid Event API URL");
258 rc = EVEL_ERR_CODES.EVEL_ERR_GEN_FAIL;
265 version += "/example_vnf";
268 url = event_api_url+":"+Integer.toString(port)+path+"/eventListener/v"+version;
271 vesurl = new URL(url);
272 } catch (MalformedURLException e) {
273 // TODO Auto-generated catch block
274 logger.info("Error in url input");
278 userpass = username + ":" + password;
280 logger.info("Starting Agent Dispatcher thread");
281 long startTime = System.currentTimeMillis();
282 Thread t = new Thread(new AgentDispatcher());
290 private static void EVEL_EXIT() {
291 // TODO Auto-generated method stub
295 private static void EVEL_ENTER() {
296 // TODO Auto-generated method stub
300 /**************************************************************************//**
301 * Handle user formatted post message
303 * @note This function handles VES 5.x formatted messages from all valid
304 * Domains and stores them in RingBuffer.
306 * @param obj VES 5.x formatted user messages with common header
307 * and optional specialized body
309 * @retval boolean True On successful acceptance False on failure
310 *****************************************************************************/
312 public static boolean evel_post_event(EvelHeader obj )
314 String data = obj.evel_json_encode_event();
315 boolean ret = ringb.put(data);
316 logger.info("Evel Post event ret:"+ret);