blob: 6b9a8ee947edbca4c1722f674db08f8f74fe96e3 [file] [log] [blame]
Ray Milkey4f5de002014-12-17 19:26:11 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2016-present Open Networking Laboratory
Ray Milkey4f5de002014-12-17 19:26:11 -08003 *
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 */
Jian Li8ae91202016-03-24 14:36:16 -070016package org.onosproject.rest.resources;
Ray Milkey4f5de002014-12-17 19:26:11 -080017
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +053018import java.io.InputStream;
19import java.net.HttpURLConnection;
20import java.util.HashMap;
21import java.util.HashSet;
22import java.util.Set;
23import java.util.concurrent.TimeUnit;
24
25import javax.ws.rs.NotFoundException;
26import javax.ws.rs.client.Entity;
27import javax.ws.rs.client.WebTarget;
28import javax.ws.rs.core.MediaType;
29import javax.ws.rs.core.Response;
30
Ray Milkey4f5de002014-12-17 19:26:11 -080031import org.hamcrest.Description;
Ray Milkeyeb5c7172015-06-23 14:59:27 -070032import org.hamcrest.Matchers;
Ray Milkey4f5de002014-12-17 19:26:11 -080033import org.hamcrest.TypeSafeMatcher;
34import org.junit.After;
35import org.junit.Before;
36import org.junit.Test;
37import org.onlab.osgi.ServiceDirectory;
38import org.onlab.osgi.TestServiceDirectory;
39import org.onlab.packet.MacAddress;
40import org.onlab.rest.BaseResource;
Jian Li2907ad22016-05-12 23:08:54 -070041import org.onosproject.app.ApplicationService;
Ray Milkey4f5de002014-12-17 19:26:11 -080042import org.onosproject.codec.CodecService;
43import org.onosproject.codec.impl.CodecManager;
Jonathan Hart9b80da82016-11-10 21:46:15 +000044import org.onosproject.codec.impl.FlowRuleCodec;
Ray Milkeyd43fe452015-05-29 09:35:12 -070045import org.onosproject.core.CoreService;
Ray Milkey4f5de002014-12-17 19:26:11 -080046import org.onosproject.core.GroupId;
47import org.onosproject.net.DefaultDevice;
48import org.onosproject.net.Device;
49import org.onosproject.net.DeviceId;
Ray Milkeyd43fe452015-05-29 09:35:12 -070050import org.onosproject.net.NetTestTools;
Ray Milkey4f5de002014-12-17 19:26:11 -080051import org.onosproject.net.device.DeviceService;
52import org.onosproject.net.flow.DefaultTrafficSelector;
53import org.onosproject.net.flow.DefaultTrafficTreatment;
54import org.onosproject.net.flow.FlowEntry;
55import org.onosproject.net.flow.FlowId;
Jonathan Hartf44e42c2015-08-04 09:58:46 -070056import org.onosproject.net.flow.FlowRule;
jcc3d4e14a2015-04-21 11:32:05 +080057import org.onosproject.net.flow.FlowRuleExtPayLoad;
Ray Milkey4f5de002014-12-17 19:26:11 -080058import org.onosproject.net.flow.FlowRuleService;
59import org.onosproject.net.flow.TrafficSelector;
60import org.onosproject.net.flow.TrafficTreatment;
61import org.onosproject.net.flow.criteria.Criterion;
62import org.onosproject.net.flow.instructions.Instruction;
jcc3d4e14a2015-04-21 11:32:05 +080063
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +053064import com.eclipsesource.json.Json;
65import com.eclipsesource.json.JsonArray;
66import com.eclipsesource.json.JsonObject;
67import com.google.common.collect.ImmutableSet;
Ray Milkey4f5de002014-12-17 19:26:11 -080068
Thiago Santos877914d2016-07-20 18:29:29 -030069import static java.util.concurrent.TimeUnit.SECONDS;
Ray Milkey4f5de002014-12-17 19:26:11 -080070import static org.easymock.EasyMock.anyObject;
Ray Milkeyd43fe452015-05-29 09:35:12 -070071import static org.easymock.EasyMock.anyShort;
Jian Li2907ad22016-05-12 23:08:54 -070072import static org.easymock.EasyMock.anyString;
Ray Milkey4f5de002014-12-17 19:26:11 -080073import static org.easymock.EasyMock.createMock;
74import static org.easymock.EasyMock.expect;
Ray Milkeyd43fe452015-05-29 09:35:12 -070075import static org.easymock.EasyMock.expectLastCall;
Ray Milkey4f5de002014-12-17 19:26:11 -080076import static org.easymock.EasyMock.replay;
77import static org.easymock.EasyMock.verify;
78import static org.hamcrest.Matchers.containsString;
79import static org.hamcrest.Matchers.hasSize;
80import static org.hamcrest.Matchers.is;
81import static org.hamcrest.Matchers.not;
82import static org.hamcrest.Matchers.notNullValue;
83import static org.junit.Assert.assertThat;
84import static org.junit.Assert.fail;
Ray Milkeyeb5c7172015-06-23 14:59:27 -070085import static org.onosproject.net.NetTestTools.APP_ID;
Ray Milkey4f5de002014-12-17 19:26:11 -080086
87/**
88 * Unit tests for Flows REST APIs.
89 */
Ray Milkey9c3d3362015-01-28 10:39:56 -080090public class FlowsResourceTest extends ResourceTest {
Ray Milkey4f5de002014-12-17 19:26:11 -080091 final FlowRuleService mockFlowService = createMock(FlowRuleService.class);
Ray Milkeyd43fe452015-05-29 09:35:12 -070092 CoreService mockCoreService = createMock(CoreService.class);
93
Ray Milkey4f5de002014-12-17 19:26:11 -080094 final HashMap<DeviceId, Set<FlowEntry>> rules = new HashMap<>();
95
96 final DeviceService mockDeviceService = createMock(DeviceService.class);
97
98 final DeviceId deviceId1 = DeviceId.deviceId("1");
99 final DeviceId deviceId2 = DeviceId.deviceId("2");
100 final DeviceId deviceId3 = DeviceId.deviceId("3");
101 final Device device1 = new DefaultDevice(null, deviceId1, Device.Type.OTHER,
102 "", "", "", "", null);
103 final Device device2 = new DefaultDevice(null, deviceId2, Device.Type.OTHER,
104 "", "", "", "", null);
105
Jian Li2907ad22016-05-12 23:08:54 -0700106 final ApplicationService mockApplicationService = createMock(ApplicationService.class);
107
Ray Milkey4f5de002014-12-17 19:26:11 -0800108 final MockFlowEntry flow1 = new MockFlowEntry(deviceId1, 1);
109 final MockFlowEntry flow2 = new MockFlowEntry(deviceId1, 2);
110
111 final MockFlowEntry flow3 = new MockFlowEntry(deviceId2, 3);
112 final MockFlowEntry flow4 = new MockFlowEntry(deviceId2, 4);
113
114 final MockFlowEntry flow5 = new MockFlowEntry(deviceId2, 5);
115 final MockFlowEntry flow6 = new MockFlowEntry(deviceId2, 6);
116
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530117 final Set<FlowEntry> flowEntries = ImmutableSet.of(flow1, flow2, flow3, flow4, flow5, flow6);
Jian Li2907ad22016-05-12 23:08:54 -0700118
Ray Milkey4f5de002014-12-17 19:26:11 -0800119 /**
120 * Mock class for a flow entry.
121 */
122 private static class MockFlowEntry implements FlowEntry {
123 final DeviceId deviceId;
124 final long baseValue;
125 TrafficTreatment treatment;
126 TrafficSelector selector;
127
128 public MockFlowEntry(DeviceId deviceId, long id) {
129 this.deviceId = deviceId;
130 this.baseValue = id * 100;
131 }
132
133 @Override
134 public FlowEntryState state() {
135 return FlowEntryState.ADDED;
136 }
137
138 @Override
139 public long life() {
Thiago Santos877914d2016-07-20 18:29:29 -0300140 return life(SECONDS);
141 }
142
143 @Override
144 public long life(TimeUnit timeUnit) {
145 return SECONDS.convert(baseValue + 11, timeUnit);
Ray Milkey4f5de002014-12-17 19:26:11 -0800146 }
147
148 @Override
Sangsik Yoonb1b823f2016-05-16 18:55:39 +0900149 public FlowLiveType liveType() {
150 return FlowLiveType.IMMEDIATE;
151 }
152
153 @Override
Ray Milkey4f5de002014-12-17 19:26:11 -0800154 public long packets() {
155 return baseValue + 22;
156 }
157
158 @Override
159 public long bytes() {
160 return baseValue + 33;
161 }
162
163 @Override
164 public long lastSeen() {
165 return baseValue + 44;
166 }
167
168 @Override
169 public int errType() {
170 return 0;
171 }
172
173 @Override
174 public int errCode() {
175 return 0;
176 }
177
178 @Override
179 public FlowId id() {
180 final long id = baseValue + 55;
181 return FlowId.valueOf(id);
182 }
183
184 @Override
alshabib08d98982015-04-21 16:25:50 -0700185 public GroupId groupId() {
Yi Tsengfa394de2017-02-01 11:26:40 -0800186 return new GroupId(3);
Ray Milkey4f5de002014-12-17 19:26:11 -0800187 }
188
189 @Override
alshabib08d98982015-04-21 16:25:50 -0700190 public short appId() {
191 return 2;
Ray Milkey4f5de002014-12-17 19:26:11 -0800192 }
193
194 @Override
195 public int priority() {
196 return (int) (baseValue + 66);
197 }
198
199 @Override
200 public DeviceId deviceId() {
201 return deviceId;
202 }
203
204 @Override
205 public TrafficSelector selector() {
206 return selector;
207 }
208
209 @Override
210 public TrafficTreatment treatment() {
211 return treatment;
212 }
213
214 @Override
215 public int timeout() {
216 return (int) (baseValue + 77);
217 }
218
219 @Override
Murat Parlakisikc6759e82016-06-29 03:22:22 -0700220 public int hardTimeout() {
221 return 0;
222 }
223
224 @Override
225 public FlowRemoveReason reason() {
226 return FlowRemoveReason.NO_REASON;
227 }
228
229 @Override
Ray Milkey4f5de002014-12-17 19:26:11 -0800230 public boolean isPermanent() {
231 return false;
232 }
sangho11c30ac2015-01-22 14:30:55 -0800233
Yuta HIGUCHI32a53c52015-02-08 01:25:40 -0800234 @Override
alshabibdb774072015-04-20 13:13:51 -0700235 public int tableId() {
236 return 0;
237 }
jcc3d4e14a2015-04-21 11:32:05 +0800238
239 @Override
Jonathan Hartf44e42c2015-08-04 09:58:46 -0700240 public boolean exactMatch(FlowRule rule) {
241 return false;
242 }
243
244 @Override
jcc3d4e14a2015-04-21 11:32:05 +0800245 public FlowRuleExtPayLoad payLoad() {
246 return null;
247 }
Ray Milkey4f5de002014-12-17 19:26:11 -0800248 }
249
Jian Li2907ad22016-05-12 23:08:54 -0700250
251 /**
Ray Milkey4f5de002014-12-17 19:26:11 -0800252 * Populates some flows used as testing data.
253 */
254 private void setupMockFlows() {
255 flow2.treatment = DefaultTrafficTreatment.builder()
Ray Milkey4f5de002014-12-17 19:26:11 -0800256 .setEthDst(MacAddress.BROADCAST)
257 .build();
258 flow2.selector = DefaultTrafficSelector.builder()
259 .matchEthType((short) 3)
260 .matchIPProtocol((byte) 9)
261 .build();
262 flow4.treatment = DefaultTrafficTreatment.builder()
Ray Milkey4f5de002014-12-17 19:26:11 -0800263 .build();
264 final Set<FlowEntry> flows1 = new HashSet<>();
265 flows1.add(flow1);
266 flows1.add(flow2);
267
268 final Set<FlowEntry> flows2 = new HashSet<>();
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700269 flows2.add(flow3);
270 flows2.add(flow4);
Ray Milkey4f5de002014-12-17 19:26:11 -0800271
272 rules.put(deviceId1, flows1);
273 rules.put(deviceId2, flows2);
274
275 expect(mockFlowService.getFlowEntries(deviceId1))
276 .andReturn(rules.get(deviceId1)).anyTimes();
277 expect(mockFlowService.getFlowEntries(deviceId2))
278 .andReturn(rules.get(deviceId2)).anyTimes();
279 }
280
281 /**
282 * Sets up the global values for all the tests.
283 */
284 @Before
Ray Milkeyed0b1662015-02-05 09:34:29 -0800285 public void setUpTest() {
Ray Milkey4f5de002014-12-17 19:26:11 -0800286 // Mock device service
287 expect(mockDeviceService.getDevice(deviceId1))
288 .andReturn(device1);
289 expect(mockDeviceService.getDevice(deviceId2))
290 .andReturn(device2);
291 expect(mockDeviceService.getDevices())
292 .andReturn(ImmutableSet.of(device1, device2));
293
Ray Milkeyd43fe452015-05-29 09:35:12 -0700294 // Mock Core Service
295 expect(mockCoreService.getAppId(anyShort()))
296 .andReturn(NetTestTools.APP_ID).anyTimes();
Jian Li2907ad22016-05-12 23:08:54 -0700297 expect(mockCoreService.getAppId(anyString()))
298 .andReturn(NetTestTools.APP_ID).anyTimes();
Jonathan Hart9b80da82016-11-10 21:46:15 +0000299 expect(mockCoreService.registerApplication(FlowRuleCodec.REST_APP_ID))
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700300 .andReturn(APP_ID).anyTimes();
Ray Milkeyd43fe452015-05-29 09:35:12 -0700301 replay(mockCoreService);
302
Ray Milkey4f5de002014-12-17 19:26:11 -0800303 // Register the services needed for the test
304 final CodecManager codecService = new CodecManager();
305 codecService.activate();
306 ServiceDirectory testDirectory =
307 new TestServiceDirectory()
308 .add(FlowRuleService.class, mockFlowService)
309 .add(DeviceService.class, mockDeviceService)
Ray Milkeyd43fe452015-05-29 09:35:12 -0700310 .add(CodecService.class, codecService)
Jian Li2907ad22016-05-12 23:08:54 -0700311 .add(CoreService.class, mockCoreService)
312 .add(ApplicationService.class, mockApplicationService);
Ray Milkey4f5de002014-12-17 19:26:11 -0800313
314 BaseResource.setServiceDirectory(testDirectory);
315 }
316
317 /**
318 * Cleans up and verifies the mocks.
Ray Milkey4f5de002014-12-17 19:26:11 -0800319 */
320 @After
Ray Milkeyed0b1662015-02-05 09:34:29 -0800321 public void tearDownTest() {
Ray Milkey4f5de002014-12-17 19:26:11 -0800322 verify(mockFlowService);
Ray Milkeyd43fe452015-05-29 09:35:12 -0700323 verify(mockCoreService);
Ray Milkey4f5de002014-12-17 19:26:11 -0800324 }
325
326 /**
327 * Hamcrest matcher to check that a flow representation in JSON matches
328 * the actual flow entry.
329 */
Jian Li2907ad22016-05-12 23:08:54 -0700330 public static class FlowEntryJsonMatcher extends TypeSafeMatcher<JsonObject> {
Ray Milkey4f5de002014-12-17 19:26:11 -0800331 private final FlowEntry flow;
Ray Milkeybe539db2015-09-04 11:00:43 -0700332 private final String expectedAppId;
Ray Milkey4f5de002014-12-17 19:26:11 -0800333 private String reason = "";
334
Jian Li2907ad22016-05-12 23:08:54 -0700335 public FlowEntryJsonMatcher(FlowEntry flowValue, String expectedAppIdValue) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800336 flow = flowValue;
Ray Milkeybe539db2015-09-04 11:00:43 -0700337 expectedAppId = expectedAppIdValue;
Ray Milkey4f5de002014-12-17 19:26:11 -0800338 }
339
340 @Override
341 public boolean matchesSafely(JsonObject jsonFlow) {
342 // check id
343 final String jsonId = jsonFlow.get("id").asString();
344 final String flowId = Long.toString(flow.id().value());
345 if (!jsonId.equals(flowId)) {
346 reason = "id " + flow.id().toString();
347 return false;
348 }
349
350 // check application id
Ray Milkeybe539db2015-09-04 11:00:43 -0700351 final String jsonAppId = jsonFlow.get("appId").asString();
352 if (!jsonAppId.equals(expectedAppId)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800353 reason = "appId " + Short.toString(flow.appId());
354 return false;
355 }
356
357 // check device id
358 final String jsonDeviceId = jsonFlow.get("deviceId").asString();
359 if (!jsonDeviceId.equals(flow.deviceId().toString())) {
360 reason = "deviceId " + flow.deviceId();
361 return false;
362 }
363
364 // check treatment and instructions array
365 if (flow.treatment() != null) {
366 final JsonObject jsonTreatment = jsonFlow.get("treatment").asObject();
367 final JsonArray jsonInstructions = jsonTreatment.get("instructions").asArray();
Ray Milkey42507352015-03-20 15:16:10 -0700368 if (flow.treatment().immediate().size() != jsonInstructions.size()) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800369 reason = "instructions array size of " +
Ray Milkey42507352015-03-20 15:16:10 -0700370 Integer.toString(flow.treatment().immediate().size());
Ray Milkey4f5de002014-12-17 19:26:11 -0800371 return false;
372 }
Ray Milkey42507352015-03-20 15:16:10 -0700373 for (final Instruction instruction : flow.treatment().immediate()) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800374 boolean instructionFound = false;
Ray Milkey4f5de002014-12-17 19:26:11 -0800375 for (int instructionIndex = 0; instructionIndex < jsonInstructions.size(); instructionIndex++) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800376 final String jsonType =
377 jsonInstructions.get(instructionIndex)
378 .asObject().get("type").asString();
379 final String instructionType = instruction.type().name();
380 if (jsonType.equals(instructionType)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800381 instructionFound = true;
382 }
383 }
384 if (!instructionFound) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800385 reason = "instruction " + instruction.toString();
Ray Milkey4f5de002014-12-17 19:26:11 -0800386 return false;
387 }
388 }
389 }
390
391 // check selector and criteria array
392 if (flow.selector() != null) {
393 final JsonObject jsonTreatment = jsonFlow.get("selector").asObject();
394 final JsonArray jsonCriteria = jsonTreatment.get("criteria").asArray();
395 if (flow.selector().criteria().size() != jsonCriteria.size()) {
396 reason = "criteria array size of " +
397 Integer.toString(flow.selector().criteria().size());
398 return false;
399 }
400 for (final Criterion criterion : flow.selector().criteria()) {
401 boolean criterionFound = false;
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800402
Ray Milkey4f5de002014-12-17 19:26:11 -0800403 for (int criterionIndex = 0; criterionIndex < jsonCriteria.size(); criterionIndex++) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800404 final String jsonType =
405 jsonCriteria.get(criterionIndex)
406 .asObject().get("type").asString();
407 final String criterionType = criterion.type().name();
408 if (jsonType.equals(criterionType)) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800409 criterionFound = true;
410 }
411 }
412 if (!criterionFound) {
Ray Milkeyc95bb9d2015-01-06 10:28:24 -0800413 reason = "criterion " + criterion.toString();
Ray Milkey4f5de002014-12-17 19:26:11 -0800414 return false;
415 }
416 }
417 }
418
419 return true;
420 }
421
422 @Override
423 public void describeTo(Description description) {
424 description.appendText(reason);
425 }
426 }
427
428 /**
429 * Factory to allocate a flow matcher.
430 *
431 * @param flow flow object we are looking for
432 * @return matcher
433 */
Jian Li2907ad22016-05-12 23:08:54 -0700434 private static FlowEntryJsonMatcher matchesFlow(FlowEntry flow, String expectedAppName) {
435 return new FlowEntryJsonMatcher(flow, expectedAppName);
Ray Milkey4f5de002014-12-17 19:26:11 -0800436 }
437
438 /**
439 * Hamcrest matcher to check that a flow is represented properly in a JSON
440 * array of flows.
441 */
Jian Li2907ad22016-05-12 23:08:54 -0700442 public static class FlowEntryJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
Ray Milkey4f5de002014-12-17 19:26:11 -0800443 private final FlowEntry flow;
444 private String reason = "";
445
Jian Li2907ad22016-05-12 23:08:54 -0700446 public FlowEntryJsonArrayMatcher(FlowEntry flowValue) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800447 flow = flowValue;
448 }
449
450 @Override
451 public boolean matchesSafely(JsonArray json) {
452 boolean flowFound = false;
453
454 for (int jsonFlowIndex = 0; jsonFlowIndex < json.size();
455 jsonFlowIndex++) {
456
457 final JsonObject jsonFlow = json.get(jsonFlowIndex).asObject();
458
459 final String flowId = Long.toString(flow.id().value());
460 final String jsonFlowId = jsonFlow.get("id").asString();
461 if (jsonFlowId.equals(flowId)) {
462 flowFound = true;
463
464 // We found the correct flow, check attribute values
Ray Milkeybe539db2015-09-04 11:00:43 -0700465 assertThat(jsonFlow, matchesFlow(flow, APP_ID.name()));
Ray Milkey4f5de002014-12-17 19:26:11 -0800466 }
467 }
468 if (!flowFound) {
469 reason = "Flow with id " + flow.id().toString() + " not found";
470 return false;
471 } else {
472 return true;
473 }
474 }
475
476 @Override
477 public void describeTo(Description description) {
478 description.appendText(reason);
479 }
480 }
481
482 /**
483 * Factory to allocate a flow array matcher.
484 *
485 * @param flow flow object we are looking for
486 * @return matcher
487 */
Jian Li2907ad22016-05-12 23:08:54 -0700488 private static FlowEntryJsonArrayMatcher hasFlow(FlowEntry flow) {
489 return new FlowEntryJsonArrayMatcher(flow);
490 }
491
492 /**
493 * Hamcrest matcher to check that a flow representation in JSON matches
494 * the actual flow rule.
495 */
496 public static class FlowRuleJsonMatcher extends TypeSafeMatcher<JsonObject> {
497 private final FlowRule flow;
498 private final String expectedAppId;
499 private String reason = "";
500
501 public FlowRuleJsonMatcher(FlowRule flowValue, String expectedAppIdValue) {
502 flow = flowValue;
503 expectedAppId = expectedAppIdValue;
504 }
505
506 @Override
507 public boolean matchesSafely(JsonObject jsonFlow) {
508 // check id
509 final String jsonId = jsonFlow.get("id").asString();
510 final String flowId = Long.toString(flow.id().value());
511 if (!jsonId.equals(flowId)) {
512 reason = "id " + flow.id().toString();
513 return false;
514 }
515
516 // check application id
517 final String jsonAppId = jsonFlow.get("appId").asString();
518 if (!jsonAppId.equals(expectedAppId)) {
519 reason = "appId " + Short.toString(flow.appId());
520 return false;
521 }
522
523 // check device id
524 final String jsonDeviceId = jsonFlow.get("deviceId").asString();
525 if (!jsonDeviceId.equals(flow.deviceId().toString())) {
526 reason = "deviceId " + flow.deviceId();
527 return false;
528 }
529
530 // check treatment and instructions array
531 if (flow.treatment() != null) {
532 final JsonObject jsonTreatment = jsonFlow.get("treatment").asObject();
533 final JsonArray jsonInstructions = jsonTreatment.get("instructions").asArray();
534 if (flow.treatment().immediate().size() != jsonInstructions.size()) {
535 reason = "instructions array size of " +
536 Integer.toString(flow.treatment().immediate().size());
537 return false;
538 }
539 for (final Instruction instruction : flow.treatment().immediate()) {
540 boolean instructionFound = false;
541 for (int instructionIndex = 0; instructionIndex < jsonInstructions.size(); instructionIndex++) {
542 final String jsonType =
543 jsonInstructions.get(instructionIndex)
544 .asObject().get("type").asString();
545 final String instructionType = instruction.type().name();
546 if (jsonType.equals(instructionType)) {
547 instructionFound = true;
548 }
549 }
550 if (!instructionFound) {
551 reason = "instruction " + instruction.toString();
552 return false;
553 }
554 }
555 }
556
557 // check selector and criteria array
558 if (flow.selector() != null) {
559 final JsonObject jsonTreatment = jsonFlow.get("selector").asObject();
560 final JsonArray jsonCriteria = jsonTreatment.get("criteria").asArray();
561 if (flow.selector().criteria().size() != jsonCriteria.size()) {
562 reason = "criteria array size of " +
563 Integer.toString(flow.selector().criteria().size());
564 return false;
565 }
566 for (final Criterion criterion : flow.selector().criteria()) {
567 boolean criterionFound = false;
568
569 for (int criterionIndex = 0; criterionIndex < jsonCriteria.size(); criterionIndex++) {
570 final String jsonType =
571 jsonCriteria.get(criterionIndex)
572 .asObject().get("type").asString();
573 final String criterionType = criterion.type().name();
574 if (jsonType.equals(criterionType)) {
575 criterionFound = true;
576 }
577 }
578 if (!criterionFound) {
579 reason = "criterion " + criterion.toString();
580 return false;
581 }
582 }
583 }
584
585 return true;
586 }
587
588 @Override
589 public void describeTo(Description description) {
590 description.appendText(reason);
591 }
592 }
593
594 /**
595 * Factory to allocate a flow matcher.
596 *
597 * @param flow flow rule object we are looking for
598 * @return matcher
599 */
600 private static FlowRuleJsonMatcher matchesFlowRule(FlowRule flow, String expectedAppName) {
601 return new FlowRuleJsonMatcher(flow, expectedAppName);
602 }
603
604 /**
605 * Hamcrest matcher to check that a flow is represented properly in a JSON
606 * array of flow rules.
607 */
608 public static class FlowRuleJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
609 private final FlowRule flow;
610 private String reason = "";
611
612 public FlowRuleJsonArrayMatcher(FlowRule flowValue) {
613 flow = flowValue;
614 }
615
616 @Override
617 public boolean matchesSafely(JsonArray json) {
618 boolean flowFound = false;
619
620 for (int jsonFlowIndex = 0; jsonFlowIndex < json.size();
621 jsonFlowIndex++) {
622
623 final JsonObject jsonFlow = json.get(jsonFlowIndex).asObject();
624
625 final String flowId = Long.toString(flow.id().value());
626 final String jsonFlowId = jsonFlow.get("id").asString();
627 if (jsonFlowId.equals(flowId)) {
628 flowFound = true;
629
630 // We found the correct flow, check attribute values
631 assertThat(jsonFlow, matchesFlowRule(flow, APP_ID.name()));
632 }
633 }
634 if (!flowFound) {
635 reason = "Flow with id " + flow.id().toString() + " not found";
636 return false;
637 } else {
638 return true;
639 }
640 }
641
642 @Override
643 public void describeTo(Description description) {
644 description.appendText(reason);
645 }
646 }
647
648 /**
649 * Factory to allocate a flow array matcher.
650 *
651 * @param flow flow rule object we are looking for
652 * @return matcher
653 */
654 private static FlowRuleJsonArrayMatcher hasFlowRule(FlowRule flow) {
655 return new FlowRuleJsonArrayMatcher(flow);
Ray Milkey4f5de002014-12-17 19:26:11 -0800656 }
657
658 /**
659 * Tests the result of the rest api GET when there are no flows.
660 */
661 @Test
662 public void testFlowsEmptyArray() {
663 expect(mockFlowService.getFlowEntries(deviceId1))
664 .andReturn(null).anyTimes();
665 expect(mockFlowService.getFlowEntries(deviceId2))
666 .andReturn(null).anyTimes();
667 replay(mockFlowService);
668 replay(mockDeviceService);
Jian Li9d616492016-03-09 10:52:49 -0800669 final WebTarget wt = target();
670 final String response = wt.path("flows").request().get(String.class);
Ray Milkey4f5de002014-12-17 19:26:11 -0800671 assertThat(response, is("{\"flows\":[]}"));
672 }
673
674 /**
675 * Tests the result of the rest api GET when there are active flows.
676 */
677 @Test
678 public void testFlowsPopulatedArray() {
679 setupMockFlows();
680 replay(mockFlowService);
681 replay(mockDeviceService);
Jian Li9d616492016-03-09 10:52:49 -0800682 final WebTarget wt = target();
683 final String response = wt.path("flows").request().get(String.class);
Jian Li80cfe452016-01-14 16:04:58 -0800684 final JsonObject result = Json.parse(response).asObject();
Ray Milkey4f5de002014-12-17 19:26:11 -0800685 assertThat(result, notNullValue());
686
687 assertThat(result.names(), hasSize(1));
688 assertThat(result.names().get(0), is("flows"));
689 final JsonArray jsonFlows = result.get("flows").asArray();
690 assertThat(jsonFlows, notNullValue());
691 assertThat(jsonFlows, hasFlow(flow1));
692 assertThat(jsonFlows, hasFlow(flow2));
693 assertThat(jsonFlows, hasFlow(flow3));
694 assertThat(jsonFlows, hasFlow(flow4));
695 }
696
697 /**
698 * Tests the result of a rest api GET for a device.
699 */
700 @Test
701 public void testFlowsSingleDevice() {
702 setupMockFlows();
703 final Set<FlowEntry> flows = new HashSet<>();
704 flows.add(flow5);
705 flows.add(flow6);
706 expect(mockFlowService.getFlowEntries(anyObject()))
707 .andReturn(flows).anyTimes();
708 replay(mockFlowService);
709 replay(mockDeviceService);
Jian Li9d616492016-03-09 10:52:49 -0800710 final WebTarget wt = target();
711 final String response = wt.path("flows/" + deviceId3).request().get(String.class);
Jian Li80cfe452016-01-14 16:04:58 -0800712 final JsonObject result = Json.parse(response).asObject();
Ray Milkey4f5de002014-12-17 19:26:11 -0800713 assertThat(result, notNullValue());
714
715 assertThat(result.names(), hasSize(1));
716 assertThat(result.names().get(0), is("flows"));
717 final JsonArray jsonFlows = result.get("flows").asArray();
718 assertThat(jsonFlows, notNullValue());
719 assertThat(jsonFlows, hasFlow(flow5));
720 assertThat(jsonFlows, hasFlow(flow6));
721 }
722
723 /**
724 * Tests the result of a rest api GET for a device.
725 */
726 @Test
727 public void testFlowsSingleDeviceWithFlowId() {
728 setupMockFlows();
729 final Set<FlowEntry> flows = new HashSet<>();
730 flows.add(flow5);
731 flows.add(flow6);
732 expect(mockFlowService.getFlowEntries(anyObject()))
733 .andReturn(flows).anyTimes();
734 replay(mockFlowService);
735 replay(mockDeviceService);
Jian Li9d616492016-03-09 10:52:49 -0800736 final WebTarget wt = target();
737 final String response = wt.path("flows/" + deviceId3 + "/"
738 + Long.toString(flow5.id().value())).request().get(String.class);
Jian Li80cfe452016-01-14 16:04:58 -0800739 final JsonObject result = Json.parse(response).asObject();
Ray Milkey4f5de002014-12-17 19:26:11 -0800740 assertThat(result, notNullValue());
741
742 assertThat(result.names(), hasSize(1));
743 assertThat(result.names().get(0), is("flows"));
744 final JsonArray jsonFlows = result.get("flows").asArray();
745 assertThat(jsonFlows, notNullValue());
746 assertThat(jsonFlows, hasFlow(flow5));
747 assertThat(jsonFlows, not(hasFlow(flow6)));
748 }
749
750 /**
751 * Tests that a fetch of a non-existent device object throws an exception.
752 */
753 @Test
754 public void testBadGet() {
Jian Li9d616492016-03-09 10:52:49 -0800755 expect(mockFlowService.getFlowEntries(anyObject()))
Ray Milkey4f5de002014-12-17 19:26:11 -0800756 .andReturn(null).anyTimes();
757 replay(mockFlowService);
758 replay(mockDeviceService);
759
Jian Li9d616492016-03-09 10:52:49 -0800760 WebTarget wt = target();
Ray Milkey4f5de002014-12-17 19:26:11 -0800761 try {
Jian Li9d616492016-03-09 10:52:49 -0800762 wt.path("flows/0").request().get(String.class);
Ray Milkey4f5de002014-12-17 19:26:11 -0800763 fail("Fetch of non-existent device did not throw an exception");
Jian Li9d616492016-03-09 10:52:49 -0800764 } catch (NotFoundException ex) {
Ray Milkey4f5de002014-12-17 19:26:11 -0800765 assertThat(ex.getMessage(),
Jian Li9d616492016-03-09 10:52:49 -0800766 containsString("HTTP 404 Not Found"));
Ray Milkey4f5de002014-12-17 19:26:11 -0800767 }
768 }
Ray Milkeyd43fe452015-05-29 09:35:12 -0700769
770 /**
771 * Tests creating a flow with POST.
772 */
773 @Test
Jian Li2907ad22016-05-12 23:08:54 -0700774 public void testPostWithoutAppId() {
Jonathan Hart9b80da82016-11-10 21:46:15 +0000775 mockFlowService.applyFlowRules(anyObject());
776 expectLastCall();
Ray Milkeyd43fe452015-05-29 09:35:12 -0700777 replay(mockFlowService);
778
Jian Li9d616492016-03-09 10:52:49 -0800779 WebTarget wt = target();
Phaneendra Manda2be2f882015-11-11 15:23:40 +0530780 InputStream jsonStream = FlowsResourceTest.class
Ray Milkeyb82c42b2015-06-30 09:42:20 -0700781 .getResourceAsStream("post-flow.json");
Ray Milkeyd43fe452015-05-29 09:35:12 -0700782
Jian Li9d616492016-03-09 10:52:49 -0800783 Response response = wt.path("flows/of:0000000000000001")
784 .request(MediaType.APPLICATION_JSON_TYPE)
785 .post(Entity.json(jsonStream));
Jonathan Hart9b80da82016-11-10 21:46:15 +0000786 assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
787 String location = response.getLocation().getPath();
788 assertThat(location, Matchers.startsWith("/flows/of:0000000000000001/"));
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700789 }
790
791 /**
Jian Li2907ad22016-05-12 23:08:54 -0700792 * Tests creating a flow with POST while specifying application identifier.
793 */
794 @Test
795 public void testPostWithAppId() {
796 mockFlowService.applyFlowRules(anyObject());
797 expectLastCall();
798 replay(mockFlowService);
799
800 WebTarget wt = target();
801 InputStream jsonStream = FlowsResourceTest.class
802 .getResourceAsStream("post-flow.json");
803
804 Response response = wt.path("flows/of:0000000000000001")
805 .queryParam("appId", "org.onosproject.rest")
806 .request(MediaType.APPLICATION_JSON_TYPE)
807 .post(Entity.json(jsonStream));
808 assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
809 String location = response.getLocation().getPath();
810 assertThat(location, Matchers.startsWith("/flows/of:0000000000000001/"));
811 }
812
813 /**
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700814 * Tests deleting a flow.
815 */
816 @Test
817 public void testDelete() {
818 setupMockFlows();
819 mockFlowService.removeFlowRules(anyObject());
820 expectLastCall();
821 replay(mockFlowService);
822
Jian Li9d616492016-03-09 10:52:49 -0800823 WebTarget wt = target();
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700824
825 String location = "/flows/1/155";
826
Jian Li9d616492016-03-09 10:52:49 -0800827 Response deleteResponse = wt.path(location)
828 .request(MediaType.APPLICATION_JSON_TYPE)
829 .delete();
Ray Milkeyeb5c7172015-06-23 14:59:27 -0700830 assertThat(deleteResponse.getStatus(),
831 is(HttpURLConnection.HTTP_NO_CONTENT));
Ray Milkeyd43fe452015-05-29 09:35:12 -0700832 }
Jian Li2907ad22016-05-12 23:08:54 -0700833
834 /**
835 * Tests the result of a rest api GET for an application.
836 */
837 @Test
838 public void testGetFlowByAppId() {
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530839 setupMockFlows();
Jian Li2907ad22016-05-12 23:08:54 -0700840
841 expect(mockApplicationService.getId(anyObject())).andReturn(APP_ID).anyTimes();
842 replay(mockApplicationService);
843
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530844 expect(mockFlowService.getFlowEntriesById(APP_ID)).andReturn(flowEntries).anyTimes();
Jian Li2907ad22016-05-12 23:08:54 -0700845 replay(mockFlowService);
846
847 final WebTarget wt = target();
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530848 final String response = wt.path("/flows/application/1").request().get(String.class);
Jian Li2907ad22016-05-12 23:08:54 -0700849 final JsonObject result = Json.parse(response).asObject();
850 assertThat(result, notNullValue());
851
852 assertThat(result.names(), hasSize(1));
853 assertThat(result.names().get(0), is("flows"));
854 final JsonArray jsonFlows = result.get("flows").asArray();
855 assertThat(jsonFlows, notNullValue());
Bharath Thiruveedula99849dc2016-11-17 22:04:38 +0530856 assertThat(jsonFlows, hasFlowRule(flow1));
857 assertThat(jsonFlows, hasFlowRule(flow2));
858 assertThat(jsonFlows, hasFlowRule(flow3));
859 assertThat(jsonFlows, hasFlowRule(flow4));
Jian Li2907ad22016-05-12 23:08:54 -0700860 }
861
862 /**
863 * Tests the result of a rest api DELETE for an application.
864 */
865 @Test
866 public void testRemoveFlowByAppId() {
867 expect(mockApplicationService.getId(anyObject())).andReturn(APP_ID).anyTimes();
868 replay(mockApplicationService);
869
870 mockFlowService.removeFlowRulesById(APP_ID);
871 expectLastCall();
872 replay(mockFlowService);
873
874 WebTarget wt = target();
875
876 String location = "/flows/application/1";
877
878 Response deleteResponse = wt.path(location)
879 .request()
880 .delete();
881 assertThat(deleteResponse.getStatus(),
882 is(HttpURLConnection.HTTP_NO_CONTENT));
883 }
Ray Milkey4f5de002014-12-17 19:26:11 -0800884}