Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add priority to alert model, add sorting in display of Alerts page #77

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Send data through request parameters
  • Loading branch information
cyu6 committed Sep 4, 2020

Verified

This commit was signed with the committer’s verified signature.
xenide A.L.
commit c362f88dd49a14f4b4b9e0e8147b6f8dcbed299e
Original file line number Diff line number Diff line change
@@ -58,9 +58,8 @@ public void doGet(HttpServletRequest request, HttpServletResponse response)
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String[] data = processRequestBody(request);
Long id = Long.parseLong(data[0]);
String priority = data[1];
Long id = Long.parseLong(request.getParameter("id"));
String priority = request.getParameter("priority");

DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
try {
@@ -71,22 +70,4 @@ public void doPost(HttpServletRequest request, HttpServletResponse response)
throw new ServletException(e);
}
}

/**
* Read from the request body, which contains data in the format "alertId statusToChangeTo".
* For example, the body could be "4785074604081152 RESOLVED".
*/
private String[] processRequestBody(HttpServletRequest request)
throws IOException, ServletException {
BufferedReader reader = request.getReader();
String body = reader.readLine();
if (body == null) {
throw new ServletException(EMPTY_BODY_ERROR);
}
String[] data = body.split(" ");
if (data.length != 2) {
throw new ServletException(WRONG_ALERT_DATA);
}
return data;
}
}
Original file line number Diff line number Diff line change
@@ -46,8 +46,6 @@
public class AlertsDataServlet extends HttpServlet {

private static final int DEFAULT_ALERTS_LIMIT = 5;
private static final String EMPTY_BODY_ERROR = "No data was sent in HTTP request body.";
private static final String WRONG_ALERT_DATA = "Incorrect alert data sent in HTTP request.";
private static final Logger log = Logger.getLogger(AlertsDataServlet.class.getName());

@Override
@@ -76,9 +74,8 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) thro
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String[] data = processRequestBody(request);
Long id = Long.parseLong(data[0]);
String status = data[1];
Long id = Long.parseLong(request.getParameter("id"));
String status = request.getParameter("status");

DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
try {
@@ -89,22 +86,4 @@ public void doPost(HttpServletRequest request, HttpServletResponse response)
throw new ServletException(e);
}
}

/**
* Read from the request body, which contains data in the format "alertId statusToChangeTo".
* For example, the body could be "4785074604081152 RESOLVED".
*/
private String[] processRequestBody(HttpServletRequest request)
throws IOException, ServletException {
BufferedReader reader = request.getReader();
String body = reader.readLine();
if (body == null) {
throw new ServletException(EMPTY_BODY_ERROR);
}
String[] data = body.split(" ");
if (data.length != 2) {
throw new ServletException(WRONG_ALERT_DATA);
}
return data;
}
}
Original file line number Diff line number Diff line change
@@ -29,7 +29,8 @@ public DummyAlertGenerator(AnomalyGenerator anomalyGenerator) {
alerts = new ArrayList<Alert>();
for (int k = 0; k < SET_ALERT_GROUP_SIZE; k++) {
alerts.add(Alert.createAlertWithoutId(Timestamp.getDummyTimestamp(k),
anomalyGenerator.getAnomalies(), Alert.StatusType.UNRESOLVED, Alert.PriorityLevel.P2));
anomalyGenerator.getAnomalies(), Alert.StatusType.UNRESOLVED,
Alert.PriorityLevel.P2));
}
}

Original file line number Diff line number Diff line change
@@ -50,7 +50,8 @@ private static ImmutableList<Alert> groupAnomaliesToAlerts(List<DataInfo> topics

return anomalyGroups.keySet().stream()
.map(key -> Alert.createAlertWithoutId(key, anomalyGroups.get(key),
Alert.StatusType.UNRESOLVED, Alert.PriorityLevel.P2)).collect(ImmutableList.toImmutableList());
Alert.StatusType.UNRESOLVED, Alert.PriorityLevel.P2))
.collect(ImmutableList.toImmutableList());
}

public List<Alert> getAlerts() {
Original file line number Diff line number Diff line change
@@ -44,7 +44,8 @@ private static ImmutableList<Alert> groupAnomaliesToAlerts(AnomalyGenerator anom
}

return anomalyGroups.keySet().stream()
.map(key -> Alert.createAlertWithoutId(key, anomalyGroups.get(key), Alert.StatusType.UNRESOLVED, Alert.PriorityLevel.P2))
.map(key -> Alert.createAlertWithoutId(key, anomalyGroups.get(key),
Alert.StatusType.UNRESOLVED, Alert.PriorityLevel.P2))
.collect(ImmutableList.toImmutableList());
}

Original file line number Diff line number Diff line change
@@ -54,11 +54,10 @@ public class AlertVisualizationServletTest {
public ExpectedException thrown = ExpectedException.none();

private static final String RESPONSE_CONTENT_TYPE = "application/json;";
private static final String REQUEST_CONTENT_TYPE = "text/plain;";
private static final String REQUEST_CHARSET = "UTF-8";
private static final String ID_PARAM = "id";
private static final String PRIORITY_PARAM = "priority";
private static final Long FAKE_ID = 1L;
private static final String EMPTY_BODY_ERROR = "No data was sent in HTTP request body.";

private static final AlertVisualizationServlet alertVisualizationServlet = new AlertVisualizationServlet();
private final LocalServiceTestHelper helper = new LocalServiceTestHelper(
@@ -115,12 +114,8 @@ public void doPost_ChangesAlertPriorityInDatastore() throws IOException, Servlet
Entity newAlertEntity = newAlert.toEntity();
datastore.put(newAlertEntity);
Long id = newAlertEntity.getKey().getId();

String data = id + " " + Alert.PriorityLevel.P0;
when(request.getReader()).thenReturn(new BufferedReader(new StringReader(data)));
when(request.getContentType()).thenReturn(REQUEST_CONTENT_TYPE);
when(request.getCharacterEncoding()).thenReturn(REQUEST_CHARSET);

when(request.getParameter(ID_PARAM)).thenReturn(Long.toString(id));
when(request.getParameter(PRIORITY_PARAM)).thenReturn(Alert.PriorityLevel.P0.name());

alertVisualizationServlet.doPost(request, response);

@@ -129,28 +124,4 @@ public void doPost_ChangesAlertPriorityInDatastore() throws IOException, Servlet
Entity resultEntity = datastore.prepare(query).asSingleEntity();
assertEquals(Alert.PriorityLevel.P0.name(), resultEntity.getProperty(Alert.PRIORITY_PROPERTY).toString());
}

@Test
public void doPost_EmptyRequestBody_ThrowsException() throws IOException, ServletException {
when(request.getReader()).thenReturn(new BufferedReader(new StringReader("")));
when(request.getContentType()).thenReturn(REQUEST_CONTENT_TYPE);
when(request.getCharacterEncoding()).thenReturn(REQUEST_CHARSET);

thrown.expect(ServletException.class);
thrown.expectMessage(EMPTY_BODY_ERROR);
alertVisualizationServlet.doPost(request, response);
}

@Test
public void doPost_EntityNotInDatastore_ThrowsException() throws IOException, ServletException {
String data = FAKE_ID + " " + Alert.StatusType.RESOLVED;
when(request.getReader()).thenReturn(new BufferedReader(new StringReader(data)));
when(request.getContentType()).thenReturn(REQUEST_CONTENT_TYPE);
when(request.getCharacterEncoding()).thenReturn(REQUEST_CHARSET);

thrown.expect(ServletException.class);
thrown.expectCause(IsInstanceOf.<Throwable>instanceOf(EntityNotFoundException.class));
alertVisualizationServlet.doPost(request, response);
}

}
Original file line number Diff line number Diff line change
@@ -55,11 +55,10 @@ public class AlertsDataServletTest {
public ExpectedException thrown = ExpectedException.none();

private static final String RESPONSE_CONTENT_TYPE = "application/json;";
private static final String REQUEST_CONTENT_TYPE = "text/plain;";
private static final String REQUEST_CHARSET = "UTF-8";
private static final Long FAKE_ID = 1L;
private static final String EMPTY_BODY_ERROR = "No data was sent in HTTP request body.";
private static final String LIMIT_PARAM = "limit";
private static final String ID_PARAM = "id";
private static final String STATUS_PARAM = "status";
private static final String FAKE_LIMIT = "2";

private static final AlertsDataServlet alertsDataServlet = new AlertsDataServlet();
@@ -144,11 +143,8 @@ public void doPost_ChangesAlertStatusInDatastore() throws IOException, ServletEx
Entity newAlertEntity = newAlert.toEntity();
datastore.put(newAlertEntity);
Long id = newAlertEntity.getKey().getId();

String data = id + " " + Alert.StatusType.RESOLVED;
when(request.getReader()).thenReturn(new BufferedReader(new StringReader(data)));
when(request.getContentType()).thenReturn(REQUEST_CONTENT_TYPE);
when(request.getCharacterEncoding()).thenReturn(REQUEST_CHARSET);
when(request.getParameter(ID_PARAM)).thenReturn(Long.toString(id));
when(request.getParameter(STATUS_PARAM)).thenReturn(Alert.StatusType.RESOLVED.name());


alertsDataServlet.doPost(request, response);
@@ -158,28 +154,4 @@ public void doPost_ChangesAlertStatusInDatastore() throws IOException, ServletEx
Entity resultEntity = datastore.prepare(query).asSingleEntity();
assertEquals(Alert.StatusType.RESOLVED.name(), resultEntity.getProperty(Alert.STATUS_PROPERTY).toString());
}

@Test
public void doPost_EmptyRequestBody_ThrowsException() throws IOException, ServletException {
when(request.getReader()).thenReturn(new BufferedReader(new StringReader("")));
when(request.getContentType()).thenReturn(REQUEST_CONTENT_TYPE);
when(request.getCharacterEncoding()).thenReturn(REQUEST_CHARSET);

thrown.expect(ServletException.class);
thrown.expectMessage(EMPTY_BODY_ERROR);
alertsDataServlet.doPost(request, response);
}

@Test
public void doPost_EntityNotInDatastore_ThrowsException() throws IOException, ServletException {
String data = FAKE_ID + " " + Alert.StatusType.RESOLVED;
when(request.getReader()).thenReturn(new BufferedReader(new StringReader(data)));
when(request.getContentType()).thenReturn(REQUEST_CONTENT_TYPE);
when(request.getCharacterEncoding()).thenReturn(REQUEST_CHARSET);

thrown.expect(ServletException.class);
thrown.expectCause(IsInstanceOf.<Throwable>instanceOf(EntityNotFoundException.class));
alertsDataServlet.doPost(request, response);
}

}
12 changes: 5 additions & 7 deletions frontend/src/AlertsManagement/AlertInfo.js
Original file line number Diff line number Diff line change
@@ -41,9 +41,8 @@ class AlertInfo extends Component {
const { alert } = this.state;

const statusToChangeTo = alert.status === UNRESOLVED_STATUS ? RESOLVED_STATUS : UNRESOLVED_STATUS;
fetch('/api/v1/alerts-data', {
method: 'POST',
body: alert.id + " " + statusToChangeTo,
fetch('/api/v1/alerts-data?id=' + alert.id + '&status=' + statusToChangeTo, {
method: 'POST'
});

const newAlert = Object.assign({}, alert);
@@ -56,15 +55,14 @@ class AlertInfo extends Component {

// We have to get the P0, P1, or P2 version to match with enum representation in backend.
const numToEnum = Object.keys(priorityLevels)[Object.values(priorityLevels).indexOf(newPriority)];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i was a bit confused on what is this numToEnum does. so you need to do the mapping with the map to convert it back?

seems the priority is just the "0", "1", "2" (the numerical value) etc for easier sorting?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup! It's for easier sorting, but to translate it back to the backend (so that the backend understands 0, 1, 2) should convert it back. If I didn't do it in the frontend, I think I would have to do it in the backend anyway

fetch('/api/v1/alert-visualization', {
method: 'POST',
body: alert.id + " " + numToEnum,
fetch('/api/v1/alert-visualization?id=' + alert.id + '&priority=' + numToEnum, {
method: 'POST'
});

const newAlert = Object.assign({}, alert);
newAlert.priority = newPriority;

this.setState({ alert: newAlert, priority: newPriority});
this.setState({ alert: newAlert, priority: newPriority });
}

render() {
12 changes: 6 additions & 6 deletions frontend/src/AlertsManagement/AlertInfo.test.js
Original file line number Diff line number Diff line change
@@ -67,8 +67,8 @@ describe("componentDidMount", () => {
})

describe("handleStatusChange", () => {
const SERVLET_ROUTE = '/api/v1/alerts-data';
const POST_DATA = {"body": "1987654321098765 UNRESOLVED", "method": "POST",};
const REQUEST_URL = '/api/v1/alerts-data?id=' + REQUEST_ID + '&status=UNRESOLVED';
const POST_DATA = {"method": "POST",};

beforeEach(() => {
fetch.resetMocks();
@@ -87,16 +87,16 @@ describe("handleStatusChange", () => {
});

expect(global.fetch).toHaveBeenCalledTimes(1);
expect(global.fetch).toHaveBeenCalledWith(SERVLET_ROUTE, POST_DATA);
expect(global.fetch).toHaveBeenCalledWith(REQUEST_URL, POST_DATA);
expect(wrapper.state('alert').status).toEqual(UNRESOLVED_STATUS);
});

// TODO: write tests for dealing with error response from backend (e.g. 404 code).
});

describe("handlePriorityChange", () => {
const SERVLET_ROUTE = '/api/v1/alert-visualization';
const POST_DATA = {"body": "1987654321098765 P1", "method": "POST",};
const REQUEST_URL = '/api/v1/alert-visualization?id=' + REQUEST_ID + '&priority=P1';
const POST_DATA = {"method": "POST",};

beforeEach(() => {
fetch.resetMocks();
@@ -115,7 +115,7 @@ describe("handlePriorityChange", () => {
});

expect(global.fetch).toHaveBeenCalledTimes(1);
expect(global.fetch).toHaveBeenCalledWith(SERVLET_ROUTE, POST_DATA);
expect(global.fetch).toHaveBeenCalledWith(REQUEST_URL, POST_DATA);
expect(wrapper.state('alert').priority).toEqual(priorityLevels.P1);
expect(wrapper.state('priority')).toEqual(priorityLevels.P1);
});
11 changes: 5 additions & 6 deletions frontend/src/AlertsManagement/AlertsContent.js
Original file line number Diff line number Diff line change
@@ -110,18 +110,18 @@ class AlertsContent extends Component {
const currentUncheckedIndex = unchecked.indexOf(alertId);
const currentCheckedIndex = checked.indexOf(alertId);

let changeStatus;
let statusToChangeTo;

if (currentCheckedIndex === -1 && currentUncheckedIndex !== -1) {
// Was unresolved and now want to resolve it, second check is a sanity check.
newChecked.push(alertId);
newUnchecked.splice(currentUncheckedIndex, 1);
changeStatus = RESOLVED_STATUS;
statusToChangeTo = RESOLVED_STATUS;
} else if (currentUncheckedIndex === -1 && currentCheckedIndex !== -1) {
// Was resolved and now want to unresolve it, second check is a sanity check.
newUnchecked.push(alertId);
newChecked.splice(currentCheckedIndex, 1);
changeStatus = UNRESOLVED_STATUS;
statusToChangeTo = UNRESOLVED_STATUS;
} else {
throw new Error("Misplaced alert: " + this.state.allAlerts[alertId]);
}
@@ -131,9 +131,8 @@ class AlertsContent extends Component {
checked: newChecked,
});

fetch('/api/v1/alerts-data', {
method: 'POST',
body: alertId + " " + changeStatus,
fetch('/api/v1/alerts-data?id=' + alertId + '&status=' + statusToChangeTo, {
method: 'POST'
});
};

6 changes: 3 additions & 3 deletions frontend/src/AlertsManagement/AlertsContent.test.js
Original file line number Diff line number Diff line change
@@ -107,8 +107,8 @@ describe("handleCheckbox", () => {
const editChecked = [2, 0];
const doubleChecked = [0, 2];

const SERVLET_ROUTE = '/api/v1/alerts-data';
const POST_DATA = {"body": "0 RESOLVED", "method": "POST",};
const REQUEST_URL = '/api/v1/alerts-data?id=0&status=RESOLVED';
const POST_DATA = {"method": "POST",};

let wrapper;

@@ -163,7 +163,7 @@ describe("handleCheckbox", () => {
});

expect(global.fetch).toHaveBeenCalledTimes(1);
expect(global.fetch).toHaveBeenCalledWith(SERVLET_ROUTE, POST_DATA);
expect(global.fetch).toHaveBeenCalledWith(REQUEST_URL, POST_DATA);
});

// TODO: write tests for dealing with error response from backend (e.g. 404 code).
Loading