Update License text
[vnfsdk/compliance.git] / veslibrary / ves_javalibrary / evel_javalib2 / src / evel_javalibrary / att / com / AgentMain.java
1
2 package evel_javalibrary.att.com;
3
4 /**************************************************************************//**
5  * @file
6  * Header for EVEL library
7  *
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.
11  *
12  * License
13  * -------
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
19  *
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  *****************************************************************************/
26
27 import org.apache.log4j.Logger;
28 import org.apache.log4j.Level;
29
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;
41 import java.net.URL;
42 //import java.nio.charset.StandardCharsets;
43
44
45 import javax.net.ssl.HttpsURLConnection;
46
47 import org.apache.log4j.BasicConfigurator;
48
49 /**
50  * @author Gokul Singaraju
51  */
52
53
54 public class AgentMain {
55         
56 /**************************************************************************//**
57  * Error codes
58  *
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.   */
74 }
75         
76         private static final Logger logger = Logger.getLogger(AgentMain.class);
77         
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";
83         
84         /* RingBuffer to forward messages on sending AgentDispatcher thread */
85         private static RingBuffer ringb = new RingBuffer(100);
86         
87         Thread thr;
88         
89         /* AgentDispatcher loops on messages in RingBuffer and POSTs them
90          * to external Collector
91          */
92     private static class AgentDispatcher  implements Runnable {
93       public void run() {
94  
95       String datatosend=null;  
96       for(;;){
97           if( (datatosend = (String) ringb.take()) != null )
98           {
99                   //process data
100                   
101                   logger.trace(url + "Got an event size "+datatosend.length());
102                   logger.trace(datatosend);
103                   
104                           try {
105                   
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;
116                 }
117                         
118                         //add reuqest header
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);
131                     
132                 con.setReadTimeout(15000 /* milliseconds */);
133                 con.setConnectTimeout(15000 /* milliseconds */);
134                         // Send post request
135                         con.setDoOutput(true);
136                         con.setDoInput(true);
137                   
138                     con.setFixedLengthStreamingMode(datatosend.length());
139                 OutputStream os = con.getOutputStream();
140                     BufferedWriter writer = new BufferedWriter(
141                                 new OutputStreamWriter(os, "UTF-8"));
142                     //Call writer POST
143                     writer.write(datatosend);
144                     writer.flush();
145                     writer.close();
146                     os.close(); 
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**");
152                 }
153                 else if(respCode >= HttpURLConnection.HTTP_OK && respCode < HttpURLConnection.HTTP_MULT_CHOICE )
154                 {
155                     logger.trace(url + " **OK**");
156                             }
157                             else if(respCode >= HttpURLConnection.HTTP_MULT_CHOICE  && respCode < HttpURLConnection.HTTP_BAD_REQUEST )
158                             {
159                                 logger.warn(url + " **REDIRECTION**");
160                             }
161                             else if(respCode >= HttpURLConnection.HTTP_BAD_REQUEST )
162                             {
163                                 logger.warn(url + " **SERVER ERROR**");
164
165                     InputStream es = con.getErrorStream();
166                     if( es != null)
167                     {
168                       int ret = 0;
169                       byte[] buf = null;
170                                       // read the response body
171                       while ((ret = es.read(buf)) > 0) {
172                         logger.info("Resp:"+buf);
173                       }
174                       // close the errorstream
175                       es.close();
176                     }
177                             }
178                 
179                                 
180                           } catch (IOException e) {
181                                   // TODO Auto-generated catch block
182                                   e.printStackTrace();
183                           }
184                   
185           }
186           else
187           {
188                   logger.trace(url + "Waiting for events");
189                   try {
190                                 Thread.sleep(5);
191                           } catch (InterruptedException e) {
192                                 // TODO Auto-generated catch block
193                                 e.printStackTrace();
194                           }
195           }
196       }//end for
197      }//end run
198    }//end AgentDispatcher
199     // Validate URL
200     public static boolean isValidURL(String urlStr) {
201         try {
202           URL url = new URL(urlStr);
203           return true;
204         }
205         catch (MalformedURLException e) {
206             return false;
207         }
208     }
209     
210     /**************************************************************************//**
211      * Library initialization.
212      *
213      * Initialize the EVEL library.
214      *
215      * @note  This function initializes the Java EVEL library interfaces.
216      *        Validates input parameters and starts the AgentDispatcher thread
217      *
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.
225      *
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,
232                 int port,
233             String path,
234             String topic,
235             String username,
236             String password,
237             Level level) throws IOException
238     {
239           EVEL_ERR_CODES rc = EVEL_ERR_CODES.EVEL_SUCCESS;
240           String throt_api_url = "http://127.0.0.1";
241
242           EVEL_ENTER();
243
244                   BasicConfigurator.configure();
245
246           /***************************************************************************/
247           /* Check assumptions.                                                      */
248           /***************************************************************************/
249           assert(event_api_url != null);
250           assert(port > 1024);
251           assert(throt_api_url != null);
252           assert(username != null);
253           
254           logger.setLevel(level);
255           
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;
259                   System.exit(1);
260           }
261           
262           if(path == null){
263                   path = "";
264           } else {
265                   version += "/example_vnf";
266           }
267           
268                 url = event_api_url+":"+Integer.toString(port)+path+"/eventListener/v"+version;
269                 vesurl = null;
270                 try {
271                         vesurl = new URL(url);
272                 } catch (MalformedURLException e) {
273                         // TODO Auto-generated catch block
274                         logger.info("Error in url input");
275                         e.printStackTrace();
276                         System.exit(1);
277                 }
278             userpass = username + ":" + password;
279
280         logger.info("Starting Agent Dispatcher thread");
281         long startTime = System.currentTimeMillis();
282         Thread t = new Thread(new AgentDispatcher());
283         t.start();
284           
285         EVEL_EXIT();
286         return rc; 
287         
288     }
289     
290     private static void EVEL_EXIT() {
291                 // TODO Auto-generated method stub
292                 
293         }
294
295         private static void EVEL_ENTER() {
296                 // TODO Auto-generated method stub
297                 
298         }
299         
300     /**************************************************************************//**
301      * Handle user formatted post message
302      *
303      * @note  This function handles VES 5.x formatted messages from all valid
304      *        Domains and stores them in RingBuffer.
305      *
306      * @param   obj     VES 5.x formatted user messages with common header
307      *                  and optional specialized body
308      *
309      * @retval  boolean    True  On successful acceptance False on failure
310      *****************************************************************************/
311
312         public static boolean evel_post_event(EvelHeader obj )
313     {
314             String data = obj.evel_json_encode_event();
315         boolean ret = ringb.put(data);
316         logger.info("Evel Post event ret:"+ret);
317         return ret;
318     }
319
320         
321
322 }