eff9a3ea687ed35c671ef54e4bd8dc8ccb65a846
[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  *
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         
94         private String readStream(InputStream stream) throws Exception {
95             StringBuilder builder = new StringBuilder();
96             try (BufferedReader in = new BufferedReader(new InputStreamReader(stream))) {
97                 String line;
98                 while ((line = in.readLine()) != null) {
99                     builder.append(line); // + "\r\n"(no need, json has no line breaks!)
100                 }
101                 in.close();
102             }
103             logger.error("Resp: " + builder.toString());
104             System.out.println("Resp: " + builder.toString());
105             return builder.toString();
106         }
107         
108       public void run() {
109  
110       String datatosend=null;  
111       for(;;){
112           if( (datatosend = (String) ringb.take()) != null )
113           {
114                   //process data
115                   
116                   logger.trace(url + "Got an event size "+datatosend.length());
117                   logger.trace(datatosend);
118                   
119                           try {
120                   
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;
131                 }
132                         
133                         //add reuqest header
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);
146                     
147                 con.setReadTimeout(15000 /* milliseconds */);
148                 con.setConnectTimeout(15000 /* milliseconds */);
149                         // Send post request
150                         con.setDoOutput(true);
151                         con.setDoInput(true);
152                   
153                     con.setFixedLengthStreamingMode(datatosend.length());
154                 OutputStream os = con.getOutputStream();
155                     BufferedWriter writer = new BufferedWriter(
156                                 new OutputStreamWriter(os, "UTF-8"));
157                     //Call writer POST
158                     writer.write(datatosend);
159                     writer.flush();
160                     writer.close();
161                     os.close(); 
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**");
167                 }
168                 else if(respCode >= HttpURLConnection.HTTP_OK && respCode < HttpURLConnection.HTTP_MULT_CHOICE )
169                 {
170                     logger.trace(url + " **OK**");
171                             }
172                             else if(respCode >= HttpURLConnection.HTTP_MULT_CHOICE  && respCode < HttpURLConnection.HTTP_BAD_REQUEST )
173                             {
174                                 logger.warn(url + " **REDIRECTION**");
175                             }
176                             else if(respCode >= HttpURLConnection.HTTP_BAD_REQUEST )
177                             {
178                                 logger.warn(url + " **SERVER ERROR**");
179
180                     InputStream es = con.getErrorStream();
181                     readStream(es);
182                             }
183                 
184                                 
185                           } catch (IOException e) {
186                                   // TODO Auto-generated catch block
187                                   e.printStackTrace();
188                           } catch (Exception e) {
189                                 // TODO Auto-generated catch block
190                                 e.printStackTrace();
191                         }
192                   
193           }
194           else
195           {
196                   logger.trace(url + "Waiting for events");
197                   try {
198                                 Thread.sleep(5);
199                           } catch (InterruptedException e) {
200                                 // TODO Auto-generated catch block
201                                 e.printStackTrace();
202                           }
203           }
204       }//end for
205      }//end run
206    }//end AgentDispatcher
207     // Validate URL
208     public static boolean isValidURL(String urlStr) {
209         try {
210           URL url = new URL(urlStr);
211           return true;
212         }
213         catch (MalformedURLException e) {
214             return false;
215         }
216     }
217     
218     /**************************************************************************//**
219      * Library initialization.
220      *
221      * Initialize the EVEL library.
222      *
223      * @note  This function initializes the Java EVEL library interfaces.
224      *        Validates input parameters and starts the AgentDispatcher thread
225      *
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.
233      *
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,
240                 int port,
241             String path,
242             String topic,
243             String username,
244             String password,
245             Level level) throws IOException
246     {
247           EVEL_ERR_CODES rc = EVEL_ERR_CODES.EVEL_SUCCESS;
248           String throt_api_url = "http://127.0.0.1";
249
250           EVEL_ENTER();
251
252                   BasicConfigurator.configure();
253
254           /***************************************************************************/
255           /* Check assumptions.                                                      */
256           /***************************************************************************/
257           assert(event_api_url != null);
258           assert(port > 1024);
259           assert(throt_api_url != null);
260           assert(username != null);
261           
262           logger.setLevel(level);
263           
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;
267                   System.exit(1);
268           }
269           
270           if(path == null){
271                   path = "";
272           } else {
273                   version += "/example_vnf";
274           }
275           
276                 url = event_api_url+":"+Integer.toString(port)+path+"/eventListener/v"+version;
277                 vesurl = null;
278                 try {
279                         vesurl = new URL(url);
280                 } catch (MalformedURLException e) {
281                         // TODO Auto-generated catch block
282                         logger.info("Error in url input");
283                         e.printStackTrace();
284                         System.exit(1);
285                 }
286             userpass = username + ":" + password;
287
288         logger.info("Starting Agent Dispatcher thread");
289         long startTime = System.currentTimeMillis();
290         Thread t = new Thread(new AgentDispatcher());
291         t.start();
292           
293         EVEL_EXIT();
294         return rc; 
295         
296     }
297     
298     private static void EVEL_EXIT() {
299                 // TODO Auto-generated method stub
300                 
301         }
302
303         private static void EVEL_ENTER() {
304                 // TODO Auto-generated method stub
305                 
306         }
307         
308     /**************************************************************************//**
309      * Handle user formatted post message
310      *
311      * @note  This function handles VES 5.x formatted messages from all valid
312      *        Domains and stores them in RingBuffer.
313      *
314      * @param   obj     VES 5.x formatted user messages with common header
315      *                  and optional specialized body
316      *
317      * @retval  boolean    True  On successful acceptance False on failure
318      *****************************************************************************/
319
320         public static boolean evel_post_event(EvelHeader obj )
321     {
322             String data = obj.evel_json_encode_event();
323         boolean ret = ringb.put(data);
324         logger.info("Evel Post event ret:"+ret);
325         return ret;
326     }
327
328         
329
330 }