blob: a019cde3b9cce2b2d111e6e8b7ccaf00d38d847e [file] [log] [blame]
William Kurkian9600b5c2018-09-20 16:05:59 -04001/*
2* Copyright 2018- Cisco
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*/
16package ves;
17
18import config.Config;
19import java.util.List;
20import org.slf4j.Logger;
21import org.slf4j.LoggerFactory;
22import com.google.gson.Gson;
23import com.google.gson.GsonBuilder;
24import com.google.gson.JsonObject;
25import com.google.gson.JsonElement;
26import org.apache.http.HttpResponse;
27import org.apache.http.client.methods.HttpPost;
28import org.apache.http.entity.StringEntity;
29import org.apache.http.impl.client.CloseableHttpClient;
30import org.apache.http.impl.client.HttpClients;
31import org.apache.http.client.HttpClient;
32import org.apache.http.client.methods.CloseableHttpResponse;
33import java.io.IOException;
34import java.io.UnsupportedEncodingException;
35
36public class VesDispatcher {
37
38 private static final Logger logger = LoggerFactory.getLogger("VesDispatcher");
39
40 private String url;
41 private String port;
42
43 private Gson gson;
44
45 private CloseableHttpClient httpClient;
46
47 public VesDispatcher(String url, String port) {
48 this.url = url;
49 this.port = port;
50
51 gson = new GsonBuilder().create();
52
53 httpClient = HttpClients.createDefault();
54 }
55
56 public int sendEvent(List<VesBlock> blocks) {
57 JsonObject root = new JsonObject();
58 JsonObject event = new JsonObject();
59 for (VesBlock block : blocks) {
60 JsonElement element = gson.toJsonTree(block);
61 event.add(block.getName(), element);
62 }
63 root.add("event", event);
64 String json = root.toString();
65 System.out.println(json);
66 int code = 0;
67
68 try {
69 HttpPost httpPost = new HttpPost(url + ":" + port+ "/eventListener/v5");
70 StringEntity input = new StringEntity(json);
71 input.setContentType("application/json");
72 httpPost.setEntity(input);
73 CloseableHttpResponse response = httpClient.execute(httpPost);
74
75 try {
76 System.out.println(response.getStatusLine());
77 code = response.getStatusLine().getStatusCode();
78 } finally {
79 response.close();
80 }
81 } catch (UnsupportedEncodingException e) {
82 logger.error("Error during http post", e);
83 logger.error(e.toString());
84 } catch (IOException e) {
85 logger.error("Error during http post", e);
86 logger.error(e.toString());
87 }
88
89 return code;
90 }
91}