Skip to content

Commit 156d1e1

Browse files
author
RAJA MARAGANI
committed
implemented rebind uploaded rules multiple times.
added documentation and download rules functionality
1 parent 14c01de commit 156d1e1

File tree

3 files changed

+196
-66
lines changed

3 files changed

+196
-66
lines changed

src/main/java/com/ericsson/ei/frontend/RulesController.java

Lines changed: 37 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,18 @@
11
package com.ericsson.ei.frontend;
22

33
import java.io.BufferedReader;
4-
import java.io.IOException;
54
import java.io.InputStream;
65
import java.io.InputStreamReader;
7-
import java.io.UnsupportedEncodingException;
8-
import java.util.ArrayList;
96

107
import javax.servlet.http.HttpServletRequest;
118

129
import org.apache.http.HttpResponse;
13-
import org.apache.http.NameValuePair;
1410
import org.apache.http.client.HttpClient;
15-
import org.apache.http.client.entity.UrlEncodedFormEntity;
1611
import org.apache.http.client.methods.HttpPost;
12+
import org.apache.http.entity.StringEntity;
1713
import org.apache.http.impl.client.HttpClients;
18-
import org.apache.http.message.BasicNameValuePair;
14+
import org.apache.http.message.BasicHeader;
15+
import org.apache.http.protocol.HTTP;
1916
import org.slf4j.Logger;
2017
import org.slf4j.LoggerFactory;
2118
import org.springframework.beans.factory.annotation.Value;
@@ -47,31 +44,32 @@ public class RulesController {
4744
private boolean useSecureHttp;
4845

4946
@CrossOrigin
50-
@RequestMapping(value = "/aggregate", method = RequestMethod.POST)
47+
@RequestMapping(value = "/rule-check/aggregation", method = RequestMethod.POST)
5148
public ResponseEntity<String> postRequests(HttpServletRequest request) {
5249

5350
String eiBackendAddressSuffix = request.getServletPath();
5451
String newRequestUrl = getEIBackendRulesRestPointAddress() + eiBackendAddressSuffix;
5552
LOG.info("Got HTTP Request with method POST.\nUrlSuffix: " + eiBackendAddressSuffix
5653
+ "\nForwarding Request to EI Backend with url: " + newRequestUrl);
57-
58-
HttpClient client = HttpClients.createDefault();
59-
HttpPost eiRequest = new HttpPost(newRequestUrl);
60-
61-
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
62-
postParameters.add(new BasicNameValuePair("listRulesJson", request.getParameter("listRulesJson")));
63-
postParameters.add(new BasicNameValuePair("listEventsJson", request.getParameter("listEventsJson")));
64-
54+
String inputReqJsonContent = "";
6555
try {
66-
eiRequest.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));
67-
} catch (UnsupportedEncodingException e1) {
56+
BufferedReader inputBufReader = new BufferedReader(request.getReader());
57+
for (String line = inputBufReader.readLine(); line != null; line = inputBufReader.readLine()) {
58+
inputReqJsonContent += line;
59+
}
60+
inputBufReader.close();
6861

69-
}
70-
eiRequest.setHeader("Content-type", "application/json");
62+
LOG.debug("Input Request JSON Content to be forwarded:\n" + inputReqJsonContent);
63+
StringEntity entity = new StringEntity(inputReqJsonContent);
64+
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
7165

72-
String jsonContent = "";
73-
HttpResponse eiResponse = null;
74-
try {
66+
HttpClient client = HttpClients.createDefault();
67+
HttpPost eiRequest = new HttpPost(newRequestUrl);
68+
eiRequest.setEntity(entity);
69+
eiRequest.setHeader("Content-type", "application/json");
70+
71+
String jsonContent = "";
72+
HttpResponse eiResponse = null;
7573
eiResponse = client.execute(eiRequest);
7674

7775
InputStream inStream = eiResponse.getEntity().getContent();
@@ -81,22 +79,27 @@ public ResponseEntity<String> postRequests(HttpServletRequest request) {
8179
}
8280
bufReader.close();
8381
inStream.close();
84-
} catch (IOException e) {
85-
LOG.error("Forward Request Errors: " + e);
86-
}
8782

88-
LOG.info("EI Http Reponse Status Code: " + eiResponse.getStatusLine().getStatusCode()
89-
+ "\nEI Recevied jsonContent:\n" + jsonContent + "\nForwarding response back to EI Frontend WebUI.");
83+
LOG.info("EI Http Reponse Status Code: " + eiResponse.getStatusLine().getStatusCode()
84+
+ "\nEI Recevied jsonContent:\n" + jsonContent
85+
+ "\nForwarding response back to EI Frontend WebUI.");
9086

91-
if (jsonContent.isEmpty()) {
92-
jsonContent = "[]";
87+
if (jsonContent.isEmpty()) {
88+
jsonContent = "[]";
89+
}
90+
91+
HttpHeaders headers = new HttpHeaders();
92+
headers.setContentType(MediaType.APPLICATION_JSON);
93+
ResponseEntity<String> responseEntity = new ResponseEntity<>(jsonContent, headers,
94+
HttpStatus.valueOf(eiResponse.getStatusLine().getStatusCode()));
95+
return responseEntity;
96+
} catch (Exception e) {
97+
LOG.error("Forward Request Errors: " + e);
98+
ResponseEntity<String> responseEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
99+
return responseEntity;
93100
}
94101

95-
HttpHeaders headers = new HttpHeaders();
96-
headers.setContentType(MediaType.APPLICATION_JSON);
97-
ResponseEntity<String> responseEntity = new ResponseEntity<>(jsonContent, headers,
98-
HttpStatus.valueOf(eiResponse.getStatusLine().getStatusCode()));
99-
return responseEntity;
102+
100103
}
101104

102105
private String getEIBackendRulesRestPointAddress() {

src/main/resources/static/js/testrules.js

Lines changed: 136 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,48 @@ jQuery(document).ready(
66

77
frontendServiceUrl = $('#frontendServiceUrl').text();
88

9+
// /Start ## Global AJAX Sender function ##################################
10+
var AjaxHttpSender = function() {
11+
};
12+
13+
AjaxHttpSender.prototype.sendAjax = function(url, type, data, callback) {
14+
$.ajax({
15+
url : url,
16+
type : type,
17+
data : data,
18+
contentType : 'application/json; charset=utf-8',
19+
dataType : "json",
20+
cache : false,
21+
beforeSend : function() {
22+
callback.beforeSend();
23+
},
24+
error : function(XMLHttpRequest, textStatus, errorThrown) {
25+
callback.error(XMLHttpRequest, textStatus, errorThrown);
26+
},
27+
success : function(data, textStatus) {
28+
callback.success(data, textStatus);
29+
},
30+
complete : function(XMLHttpRequest, textStatus) {
31+
callback.complete();
32+
}
33+
});
34+
}
35+
// /Stop ## Global AJAX Sender function ##################################
36+
37+
//Function for validating the json format, it accepts only string json
38+
function isValidJSON(str) {
39+
if (typeof (str) !== 'string') {
40+
return false;
41+
}
42+
try {
43+
JSON.parse(str);
44+
return true;
45+
} catch (e) {
46+
return false;
47+
}
48+
}
49+
50+
// Model for knockout(KO) binding
951
function AppViewModel(rulesList) {
1052
var self = this;
1153
self.rulesBindingList = ko.observableArray(rulesList);
@@ -18,6 +60,7 @@ jQuery(document).ready(
1860
return JSON.stringify(item, null, 2);
1961
};
2062

63+
//After adding a rule, this function remove the type from dropdown
2164
self.removeDropdown = function(name) {
2265
var index = self.dropdown.indexOf(name);
2366
if (index !== -1) {
@@ -26,31 +69,46 @@ jQuery(document).ready(
2669
return name;
2770
};
2871

72+
// Removing the rule
2973
self.removeRule = function(name) {
3074
self.rulesBindingList.remove(name);
3175
self.dropdown.push(name.Type);
3276
};
77+
78+
//This submit function for finding the aggregated object from the rules and events, This function internally call the ajax call
3379
self.submit = function() {
34-
var inputs = $("#eventsListID").val();
80+
var events = $("#eventsListID").val();
3581
var formRules = [];
36-
$('.formRules').each (function() {
37-
formRules.push($(this).val());
82+
$('.formRules').each(function() {
83+
try {
84+
formRules.push(JSON.parse($(this).val()));
85+
} catch (e) {
86+
$.jGrowl("Invalid json format :\n" + $(this).val(), {
87+
sticky : false,
88+
theme : 'Error'
89+
});
90+
return false;
91+
}
3892
});
39-
console.log("Rules : "+formRules.length);
40-
console.log(formRules.toString());
41-
console.log("Events : ");
42-
console.log(inputs.toString());
93+
4394
var callback = {
4495
beforeSend : function() {
4596
},
4697
success : function(data, textStatus) {
47-
var returnData = [ data ];
98+
var returnData = data;
4899
if (returnData.length > 0) {
49100
$.jGrowl("Successfully aggregated object generated", {
50101
sticky : false,
51102
theme : 'Error'
52103
});
53-
reload_table();
104+
105+
$('#aggregatedresultData').text(JSON.stringify(data, null, 2));
106+
var divText = document.getElementById("aggregatedresult").outerHTML;
107+
var myWindow = window.open('', '', 'width=700,height=1000');
108+
var doc = myWindow.document;
109+
doc.open();
110+
doc.write(divText);
111+
doc.close();
54112
}
55113
},
56114
error : function(XMLHttpRequest, textStatus, errorThrown) {
@@ -62,13 +120,18 @@ jQuery(document).ready(
62120
complete : function() {
63121
}
64122
};
65-
// Perform AJAX
66-
// var ajaxHttpSender = new AjaxHttpSender();
67-
// ajaxHttpSender.sendAjax(frontendServiceUrl + "/rules/rule-check/aggregation", "POST", ko.toJSON("{'listRulesJson':"
68-
// + self.parsedToString(self.rulesBindingList()) + ",'listEventsJson':" + self.eventsBindingList.toString() + "}"), callback);
69-
123+
var eventsValid = isValidJSON(events.toString());
124+
if (!eventsValid) {
125+
alert("Events are not a valid json format");
126+
} else {
127+
var ajaxHttpSender = new AjaxHttpSender();
128+
//console.log(JSON.stringify(JSON.parse('{"listRulesJson":' + JSON.stringify(formRules) + ',"listEventsJson":' + events.toString() + '}')));
129+
ajaxHttpSender.sendAjax(frontendServiceUrl + "/rules/rule-check/aggregation", "POST", JSON.stringify(JSON.parse('{"listRulesJson":'
130+
+ JSON.stringify(formRules) + ',"listEventsJson":' + events.toString() + '}')), callback);
131+
}
70132
};
71133

134+
// This function for adding rule
72135
self.addRule = function(viewModel, event) {
73136
var newValue = event.target.value;
74137
if (newValue != '') {
@@ -83,14 +146,19 @@ jQuery(document).ready(
83146
return self;
84147
}
85148

149+
86150
var vm = new AppViewModel([]);
87151
ko.applyBindings(vm, $("#submitButton")[0]);
88-
// ko.applyBindings(vm, $(".testTulesDOMObject")[0]);
152+
vm.rulesBindingList.push({
153+
"TemplateName" : "",
154+
"Type" : "EiffelArtifactCreatedEvent"
155+
156+
});
157+
vm.removeDropdown("EiffelArtifactCreatedEvent");
158+
ko.applyBindings(vm, $("#testTulesDOMObject")[0]);
89159

90-
$(".container").on(
91-
"click",
92-
"button.upload_rules",
93-
function(event) {
160+
//Upload events list json data
161+
$(".container").on("click","button.upload_rules", function(event) {
94162
event.stopPropagation();
95163
event.preventDefault();
96164

@@ -163,6 +231,7 @@ jQuery(document).ready(
163231
}
164232
});
165233

234+
//Upload list of events json data
166235
$(".container").on("click", "button.upload_events", function(event) {
167236
event.stopPropagation();
168237
event.preventDefault();
@@ -226,4 +295,52 @@ jQuery(document).ready(
226295
}
227296
});
228297

298+
// Download the modified rule
299+
$('.container').on('click', 'button.download_rules', function() {
300+
var formRules = [];
301+
$('.formRules').each(function() {
302+
try {
303+
formRules.push(JSON.parse($(this).val()));
304+
} catch (e) {
305+
$.jGrowl("Invalid json format :\n" + $(this).val(), {
306+
sticky : false,
307+
theme : 'Error'
308+
});
309+
return false;
310+
}
311+
});
312+
if (formRules.length !== 0) {
313+
var contentType = "application/json;charset=utf-8";
314+
var jsonData = JSON.stringify(formRules, null, 2);
315+
var fileName = "rules.json"
316+
317+
function downloadFile(data, type, title) {
318+
var link = document.createElement('a');
319+
link.setAttribute("href", "data:" + type + "," + encodeURIComponent(data));
320+
link.setAttribute("download", fileName);
321+
link.setAttribute("class", "hidden");
322+
link.click();
323+
}
324+
325+
function downloadFileMSExplorer(data, type, title) {
326+
var blob = new Blob([ data ], {
327+
type : type
328+
});
329+
window.navigator.msSaveOrOpenBlob(blob, title);
330+
}
331+
332+
if (window.navigator.msSaveOrOpenBlob) {
333+
downloadFileMSExplorer(jsonData, contentType, fileName);
334+
} else {
335+
downloadFile(jsonData, contentType, fileName);
336+
}
337+
}
338+
else{
339+
$.jGrowl("Data not available for download!", {
340+
sticky : false,
341+
theme : 'Error'
342+
});
343+
}
344+
345+
});
229346
});

0 commit comments

Comments
 (0)