Brian Stanke
Committed by Gerrit Code Review

ONOS-3658 - Adding REST APIs for query and management of device keys.

Change-Id: I3c70660a15d9085409e43d2d14120d29fd5020be
......@@ -53,6 +53,7 @@ import org.onosproject.net.intent.Constraint;
import org.onosproject.net.intent.HostToHostIntent;
import org.onosproject.net.intent.Intent;
import org.onosproject.net.intent.PointToPointIntent;
import org.onosproject.net.key.DeviceKey;
import org.onosproject.net.mcast.McastRoute;
import org.onosproject.net.meter.Band;
import org.onosproject.net.meter.Meter;
......@@ -119,6 +120,7 @@ public class CodecManager implements CodecService {
registerCodec(ForwardingObjective.class, new ForwardingObjectiveCodec());
registerCodec(NextObjective.class, new NextObjectiveCodec());
registerCodec(McastRoute.class, new McastRouteCodec());
registerCodec(DeviceKey.class, new DeviceKeyCodec());
log.info("Started");
}
......
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.codec.impl;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.onosproject.codec.CodecContext;
import org.onosproject.net.key.DeviceKey;
import org.onosproject.net.key.DeviceKeyId;
import org.onosproject.net.key.DeviceKeyService;
import org.slf4j.Logger;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Device key JSON codec.
*/
public class DeviceKeyCodec extends AnnotatedCodec<DeviceKey> {
private final Logger log = getLogger(getClass());
// JSON fieldNames
private static final String ID = "id";
private static final String TYPE = "type";
private static final String LABEL = "label";
private static final String COMMUNITY_NAME = "community_name";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
@Override
public ObjectNode encode(DeviceKey deviceKey, CodecContext context) {
checkNotNull(deviceKey, "Device key cannot be null");
DeviceKeyService service = context.getService(DeviceKeyService.class);
ObjectNode result = context.mapper().createObjectNode()
.put(ID, deviceKey.deviceKeyId().id().toString())
.put(TYPE, deviceKey.type().toString())
.put(LABEL, deviceKey.label().toString());
if (deviceKey.type().equals(DeviceKey.Type.COMMUNITY_NAME)) {
result.put(COMMUNITY_NAME, deviceKey.asCommunityName().name());
} else if (deviceKey.type().equals(DeviceKey.Type.USERNAME_PASSWORD)) {
result.put(USERNAME, deviceKey.asUsernamePassword().username().toString());
result.put(PASSWORD, deviceKey.asUsernamePassword().password().toString());
}
return annotate(result, deviceKey, context);
}
@Override
public DeviceKey decode(ObjectNode json, CodecContext context) {
if (json == null || !json.isObject()) {
return null;
}
DeviceKeyId id = DeviceKeyId.deviceKeyId(json.get(ID).asText());
DeviceKey.Type type = DeviceKey.Type.valueOf(json.get(TYPE).asText());
String label = json.get(LABEL).asText();
if (type.equals(DeviceKey.Type.COMMUNITY_NAME)) {
String communityName = json.get(COMMUNITY_NAME).asText();
return DeviceKey.createDeviceKeyUsingCommunityName(id, label, communityName);
} else if (type.equals(DeviceKey.Type.USERNAME_PASSWORD)) {
String username = json.get(USERNAME).asText();
String password = json.get(PASSWORD).asText();
return DeviceKey.createDeviceKeyUsingUsernamePassword(id, label, username, password);
} else {
log.error("Unknown device key type: ", type);
return null;
}
}
}
......@@ -45,7 +45,8 @@ public class CoreWebApplication extends AbstractWebApplication {
StatisticsWebResource.class,
MetricsWebResource.class,
FlowObjectiveWebResource.class,
MulticastRouteWebResource.class
MulticastRouteWebResource.class,
DeviceKeyWebResource.class
);
}
}
......
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.rest.resources;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.onosproject.net.key.DeviceKey;
import org.onosproject.net.key.DeviceKeyAdminService;
import org.onosproject.net.key.DeviceKeyId;
import org.onosproject.net.key.DeviceKeyService;
import org.onosproject.rest.AbstractWebResource;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
import java.io.InputStream;
import static org.onlab.util.Tools.nullIsNotFound;
/**
* Query and Manage Device Keys.
*/
@Path("keys")
public class DeviceKeyWebResource extends AbstractWebResource {
@Context
UriInfo uriInfo;
private static final String DEVICE_KEY_NOT_FOUND = "Device key was not found";
/**
* Gets all device keys.
* Returns array of all device keys.
*
* @return 200 OK
* @onos.rsModel DeviceKeysGet
*/
@GET
public Response getDeviceKeys() {
Iterable<DeviceKey> deviceKeys = get(DeviceKeyService.class).getDeviceKeys();
return ok(encodeArray(DeviceKey.class, "keys", deviceKeys)).build();
}
/**
* Get a single device key by device key unique identifier.
* Returns the specified device key.
*
* @param id device identifier
* @return 200 OK
* @onos.rsModel DeviceKeyGet
*/
@GET
@Path("{id}")
public Response getDeviceKey(@PathParam("id") String id) {
DeviceKey deviceKey = nullIsNotFound(get(DeviceKeyService.class).getDeviceKey(DeviceKeyId.deviceKeyId(id)),
DEVICE_KEY_NOT_FOUND);
return ok(codec(DeviceKey.class).encode(deviceKey, this)).build();
}
/**
* Adds a new device key from the JSON request.
*
* @param stream input JSON
* @return status of the request - CREATED if the JSON is correct,
* BAD_REQUEST if the JSON is invalid
* @onos.rsModel IntentHost
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addDeviceKey(InputStream stream) {
try {
DeviceKeyAdminService service = get(DeviceKeyAdminService.class);
ObjectNode root = (ObjectNode) mapper().readTree(stream);
DeviceKey deviceKey = codec(DeviceKey.class).decode(root, this);
service.addKey(deviceKey);
UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
.path("keys")
.path(deviceKey.deviceKeyId().id());
return Response
.created(locationBuilder.build())
.build();
} catch (IOException ioe) {
throw new IllegalArgumentException(ioe);
}
}
/**
* Removes a device key by device key identifier.
*
* @param id device identifier
* @return 200 OK
*/
@DELETE
@Path("{id}")
public Response removeDeviceKey(@PathParam("id") String id) {
DeviceKey deviceKey = nullIsNotFound(get(DeviceKeyService.class).getDeviceKey(DeviceKeyId.deviceKeyId(id)),
DEVICE_KEY_NOT_FOUND);
get(DeviceKeyAdminService.class).removeKey(DeviceKeyId.deviceKeyId(id));
return ok(codec(DeviceKey.class).encode(deviceKey, this)).build();
}
}
/*
* Copyright 2016 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.rest;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import org.hamcrest.Description;
import org.hamcrest.Matchers;
import org.hamcrest.TypeSafeMatcher;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onlab.osgi.ServiceDirectory;
import org.onlab.osgi.TestServiceDirectory;
import org.onlab.rest.BaseResource;
import org.onosproject.codec.CodecService;
import org.onosproject.codec.impl.CodecManager;
import org.onosproject.net.key.DeviceKey;
import org.onosproject.net.key.DeviceKeyAdminService;
import org.onosproject.net.key.DeviceKeyId;
import org.onosproject.net.key.DeviceKeyService;
import javax.ws.rs.core.MediaType;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashSet;
import static org.easymock.EasyMock.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
/**
* Unit tests for device key REST APIs.
*/
public class DeviceKeyWebResourceTest extends ResourceTest {
final DeviceKeyService mockDeviceKeyService = createMock(DeviceKeyService.class);
final DeviceKeyAdminService mockDeviceKeyAdminService = createMock(DeviceKeyAdminService.class);
final HashSet<DeviceKey> deviceKeySet = new HashSet<>();
private static final String ID = "id";
private static final String TYPE = "type";
private static final String LABEL = "label";
private static final String COMMUNITY_NAME = "community_name";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private final String deviceKeyId1 = "DeviceKeyId1";
private final String deviceKeyId2 = "DeviceKeyId2";
private final String deviceKeyId3 = "DeviceKeyId3";
private final String deviceKeyLabel = "DeviceKeyLabel";
private final String deviceKeyCommunityName = "DeviceKeyCommunityName";
private final String deviceKeyUsername = "DeviceKeyUsername";
private final String deviceKeyPassword = "DeviceKeyPassword";
private final DeviceKey deviceKey1 = DeviceKey.createDeviceKeyUsingCommunityName(
DeviceKeyId.deviceKeyId(deviceKeyId1), deviceKeyLabel, deviceKeyCommunityName);
private final DeviceKey deviceKey2 = DeviceKey.createDeviceKeyUsingUsernamePassword(
DeviceKeyId.deviceKeyId(deviceKeyId2), deviceKeyLabel, deviceKeyUsername, deviceKeyPassword);
/**
* Initializes test mocks and environment.
*/
@Before
public void setUpMocks() {
expect(mockDeviceKeyService.getDeviceKeys()).andReturn(deviceKeySet).anyTimes();
// Register the services needed for the test
CodecManager codecService = new CodecManager();
codecService.activate();
ServiceDirectory testDirectory =
new TestServiceDirectory()
.add(DeviceKeyService.class, mockDeviceKeyService)
.add(DeviceKeyAdminService.class, mockDeviceKeyAdminService)
.add(CodecService.class, codecService);
BaseResource.setServiceDirectory(testDirectory);
}
/**
* Verifies test mocks.
*/
@After
public void tearDownMocks() {
verify(mockDeviceKeyService);
verify(mockDeviceKeyAdminService);
}
/**
* Hamcrest matcher to check that a device key representation in JSON matches
* the actual device key.
*/
public static class DeviceKeyJsonMatcher extends TypeSafeMatcher<JsonObject> {
private final DeviceKey deviceKey;
private String reason = "";
public DeviceKeyJsonMatcher(DeviceKey deviceKeyValue) {
deviceKey = deviceKeyValue;
}
@Override
public boolean matchesSafely(JsonObject jsonHost) {
// Check the device key id
final String jsonId = jsonHost.get(ID).asString();
if (!jsonId.equals(deviceKey.deviceKeyId().id().toString())) {
reason = ID + " " + deviceKey.deviceKeyId().id().toString();
return false;
}
// Check the device key label
final String jsonLabel = jsonHost.get(LABEL).asString();
if (!jsonLabel.equals(deviceKey.label().toString())) {
reason = LABEL + " " + deviceKey.label().toString();
return false;
}
// Check the device key type
final String jsonType = jsonHost.get(TYPE).asString();
if (!jsonType.equals(deviceKey.type().toString())) {
reason = TYPE + " " + deviceKey.type().toString();
return false;
}
if (jsonType.equals(DeviceKey.Type.COMMUNITY_NAME.toString())) {
// Check the device key community name
final String jsonCommunityName = jsonHost.get(COMMUNITY_NAME).asString();
if (!jsonCommunityName.equals(deviceKey.asCommunityName().name().toString())) {
reason = COMMUNITY_NAME + " " + deviceKey.asCommunityName().name().toString();
return false;
}
} else if (jsonType.equals(DeviceKey.Type.USERNAME_PASSWORD.toString())) {
// Check the device key username
final String jsonUsername = jsonHost.get(USERNAME).asString();
if (!jsonUsername.equals(deviceKey.asUsernamePassword().username().toString())) {
reason = USERNAME + " " + deviceKey.asUsernamePassword().username().toString();
return false;
}
// Check the device key password
final String jsonPassword = jsonHost.get(PASSWORD).asString();
if (!jsonPassword.equals(deviceKey.asUsernamePassword().password().toString())) {
reason = PASSWORD + " " + deviceKey.asUsernamePassword().password().toString();
return false;
}
} else {
reason = "Unknown " + TYPE + " " + deviceKey.type().toString();
return false;
}
return true;
}
@Override
public void describeTo(Description description) {
description.appendText(reason);
}
}
/**
* Factory to allocate a device key array matcher.
*
* @param deviceKey device key object we are looking for
* @return matcher
*/
private static DeviceKeyJsonMatcher matchesDeviceKey(DeviceKey deviceKey) {
return new DeviceKeyJsonMatcher(deviceKey);
}
/**
* Hamcrest matcher to check that a device key is represented properly in a JSON
* array of device keys.
*/
public static class DeviceKeyJsonArrayMatcher extends TypeSafeMatcher<JsonArray> {
private final DeviceKey deviceKey;
private String reason = "";
public DeviceKeyJsonArrayMatcher(DeviceKey deviceKeyValue) {
deviceKey = deviceKeyValue;
}
@Override
public boolean matchesSafely(JsonArray json) {
boolean deviceKeyFound = false;
final int expectedAttributes = 5;
for (int jsonDeviceKeyIndex = 0; jsonDeviceKeyIndex < json.size();
jsonDeviceKeyIndex++) {
final JsonObject jsonHost = json.get(jsonDeviceKeyIndex).asObject();
// Device keys can have a variable number of attribute so we check
// that there is a minimum number.
if (jsonHost.names().size() < expectedAttributes) {
reason = "Found a device key with the wrong number of attributes";
return false;
}
final String jsonDeviceKeyId = jsonHost.get(ID).asString();
if (jsonDeviceKeyId.equals(deviceKey.deviceKeyId().id().toString())) {
deviceKeyFound = true;
// We found the correct device key, check the device key attribute values
assertThat(jsonHost, matchesDeviceKey(deviceKey));
}
}
if (!deviceKeyFound) {
reason = "Device key with id " + deviceKey.deviceKeyId().id().toString() + " was not found";
return false;
} else {
return true;
}
}
@Override
public void describeTo(Description description) {
description.appendText(reason);
}
}
/**
* Factory to allocate a device key array matcher.
*
* @param deviceKey device key object we are looking for
* @return matcher
*/
private static DeviceKeyJsonArrayMatcher hasDeviceKey(DeviceKey deviceKey) {
return new DeviceKeyJsonArrayMatcher(deviceKey);
}
/**
* Tests the result of the REST API GET when there are no device keys.
*/
@Test
public void testGetDeviceKeysEmptyArray() {
replay(mockDeviceKeyService);
replay(mockDeviceKeyAdminService);
WebResource rs = resource();
String response = rs.path("keys").get(String.class);
assertThat(response, is("{\"keys\":[]}"));
}
/**
* Tests the result of the REST API GET when device keys are defined.
*/
@Test
public void testGetDeviceKeysArray() {
replay(mockDeviceKeyService);
replay(mockDeviceKeyAdminService);
deviceKeySet.add(deviceKey1);
deviceKeySet.add(deviceKey2);
WebResource rs = resource();
String response = rs.path("keys").get(String.class);
assertThat(response, containsString("{\"keys\":["));
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("keys"));
final JsonArray deviceKeys = result.get("keys").asArray();
assertThat(deviceKeys, notNullValue());
assertEquals("Device keys array is not the correct size.", 2, deviceKeys.size());
assertThat(deviceKeys, hasDeviceKey(deviceKey1));
assertThat(deviceKeys, hasDeviceKey(deviceKey2));
}
/**
* Tests the result of the REST API GET using a device key identifier.
*/
@Test
public void testGetDeviceKeyById() {
deviceKeySet.add(deviceKey1);
expect(mockDeviceKeyService.getDeviceKey(DeviceKeyId.deviceKeyId(deviceKeyId1)))
.andReturn(deviceKey1)
.anyTimes();
replay(mockDeviceKeyService);
replay(mockDeviceKeyAdminService);
WebResource rs = resource();
String response = rs.path("keys/" + deviceKeyId1).get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result, matchesDeviceKey(deviceKey1));
}
/**
* Tests that a GET of a non-existent object throws an exception.
*/
@Test
public void testGetNonExistentDeviceKey() {
expect(mockDeviceKeyService.getDeviceKey(DeviceKeyId.deviceKeyId(deviceKeyId1)))
.andReturn(null)
.anyTimes();
replay(mockDeviceKeyService);
replay(mockDeviceKeyAdminService);
WebResource rs = resource();
try {
String response = rs.path("keys/" + deviceKeyId1).get(String.class);
fail("GET of a non-existent device key did not throw an exception");
} catch (UniformInterfaceException ex) {
assertThat(ex.getMessage(),
containsString("returned a response status of"));
}
}
/**
* Tests adding of new device key using POST via JSON stream.
*/
@Test
public void testPost() {
mockDeviceKeyAdminService.addKey(anyObject());
expectLastCall();
replay(mockDeviceKeyService);
replay(mockDeviceKeyAdminService);
WebResource rs = resource();
InputStream jsonStream = DeviceKeyWebResourceTest.class
.getResourceAsStream("post-device-key.json");
ClientResponse response = rs.path("keys")
.type(MediaType.APPLICATION_JSON_TYPE)
.post(ClientResponse.class, jsonStream);
assertThat(response.getStatus(), is(HttpURLConnection.HTTP_CREATED));
String location = response.getLocation().getPath();
assertThat(location, Matchers.startsWith("/keys/" + deviceKeyId3));
}
/**
* Tests adding of a null device key using POST via JSON stream.
*/
@Test
public void testPostNullDeviceKey() {
replay(mockDeviceKeyService);
replay(mockDeviceKeyAdminService);
WebResource rs = resource();
try {
String response = rs.path("keys")
.type(MediaType.APPLICATION_JSON_TYPE)
.post(String.class);
fail("POST of null device key did not throw an exception");
} catch (UniformInterfaceException ex) {
assertThat(ex.getMessage(),
containsString("returned a response status of"));
}
}
/**
* Tests removing a device key with DELETE request.
*/
@Test
public void testDelete() {
expect(mockDeviceKeyService.getDeviceKey(DeviceKeyId.deviceKeyId(deviceKeyId2)))
.andReturn(deviceKey2)
.anyTimes();
mockDeviceKeyAdminService.removeKey(anyObject());
expectLastCall();
replay(mockDeviceKeyService);
replay(mockDeviceKeyAdminService);
WebResource rs = resource();
ClientResponse response = rs.path("keys/" + deviceKeyId2)
.type(MediaType.APPLICATION_JSON_TYPE)
.delete(ClientResponse.class);
assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK));
}
/**
* Tests that a DELETE of a non-existent device key throws an exception.
*/
@Test
public void testDeleteNonExistentDeviceKey() {
expect(mockDeviceKeyService.getDeviceKey(anyObject()))
.andReturn(null)
.anyTimes();
expectLastCall();
replay(mockDeviceKeyService);
replay(mockDeviceKeyAdminService);
WebResource rs = resource();
try {
String response = rs.path("keys/" + "NON_EXISTENT_DEVICE_KEY")
.delete(String.class);
fail("Delete of a non-existent device key did not throw an exception");
} catch (UniformInterfaceException ex) {
assertThat(ex.getMessage(),
containsString("returned a response status of"));
}
}
}
\ No newline at end of file
{
"id": "DeviceKeyId3",
"type": "USERNAME_PASSWORD",
"label": "DeviceKeyLabel3",
"username": "DeviceKeyUsername3",
"password": "DeviceKeyPassword3"
}