下面列出了java.net.http.HttpResponse.BodyHandlers#com.eclipsesource.json.Json 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private JsonValue executeCommandAndGetJsonValue(String command1, String command2, String command3)
throws WalletCallException, IOException, InterruptedException
{
String strResponse = this.executeCommandAndGetSingleStringResponse(command1, command2, command3);
JsonValue response = null;
try
{
response = Json.parse(strResponse);
} catch (ParseException pe)
{
throw new WalletCallException(strResponse + "\n" + pe.getMessage() + "\n", pe);
}
return response;
}
/**
* Tests the result of a rest api GET for port pair id.
*/
@Test
public void testGetPortPairId() {
final Set<PortPair> portPairs = new HashSet<>();
portPairs.add(portPair1);
expect(portPairService.exists(anyObject())).andReturn(true).anyTimes();
expect(portPairService.getPortPair(anyObject())).andReturn(portPair1).anyTimes();
replay(portPairService);
final WebTarget wt = target();
final String response = wt.path("port_pairs/78dcd363-fc23-aeb6-f44b-56dc5e2fb3ae")
.request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
}
/**
* Tests the result of the rest api GET when there are no OFAgents.
*
* @throws IOException IO exception
*/
@Test
public void testEmptyOFAgentSet() throws IOException {
expect(mockOFAgentService.agents()).andReturn(empty).anyTimes();
replay(mockOFAgentService);
final WebTarget wt = target();
assertNotNull("WebTarget is null", wt);
assertNotNull("WebTarget request is null", wt.request());
final String response = wt.path("service/ofagents").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(response, is("{\"ofAgents\":[]}"));
verify(mockOFAgentService);
}
/**
* Tests the result of the rest api GET when there is a config.
*/
@Test
public void testConfigs() {
setUpConfigData();
final WebTarget wt = target();
final String response = wt.path("network/configuration").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.names(), hasSize(2));
JsonValue devices = result.get("devices");
Assert.assertThat(devices, notNullValue());
JsonValue device1 = devices.asObject().get("device1");
Assert.assertThat(device1, notNullValue());
JsonValue basic = device1.asObject().get("basic");
Assert.assertThat(basic, notNullValue());
checkBasicAttributes(basic);
}
/**
* Tests a GET of an applicationId entry with the given numeric id.
*/
@Test
public void getAppIdByShortId() {
expect(coreService.getAppId((short) 1)).andReturn(id1);
replay(coreService);
WebTarget wt = target();
String response = wt.path("applications/ids/entry")
.queryParam("id", 1).request().get(String.class);
JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result, matchesAppId(id1));
verify(coreService);
}
/**
* Tests the result of the rest api single subject key GET when
* there is a config.
*/
@Test
public void testSingleSubjectKeyConfig() {
setUpConfigData();
final WebTarget wt = target();
final String response = wt.path("network/configuration/devices").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
Assert.assertThat(result, notNullValue());
Assert.assertThat(result.names(), hasSize(1));
JsonValue device1 = result.asObject().get("device1");
Assert.assertThat(device1, notNullValue());
JsonValue basic = device1.asObject().get("basic");
Assert.assertThat(basic, notNullValue());
checkBasicAttributes(basic);
}
/**
* Tests the result of the REST API GET when there are valid nodes.
*/
@Test
public void testGetNodesPopulatedArray() {
expect(mockOpenstackNodeService.nodes()).
andReturn(ImmutableSet.of(openstackNode)).anyTimes();
replay(mockOpenstackNodeService);
final WebTarget wt = target();
final String response = wt.path(PATH).request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("nodes"));
final JsonArray jsonNodes = result.get("nodes").asArray();
assertThat(jsonNodes, notNullValue());
assertThat(jsonNodes.size(), is(1));
assertThat(jsonNodes, hasNode(openstackNode));
verify(mockOpenstackNodeService);
}
/**
* Tests the result of the REST API GET when there are active master roles.
*/
@Test
public void testGetLocalRole() {
expect(mockService.getLocalRole(anyObject())).andReturn(role1).anyTimes();
replay(mockService);
final WebTarget wt = target();
final String response = wt.path("mastership/" + deviceId1.toString() +
"/local").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("role"));
final String role = result.get("role").asString();
assertThat(role, notNullValue());
assertThat(role, is("MASTER"));
}
protected static String handleResponse(HttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode >= 200 && statusCode < 300) {
HttpEntity entity = response.getEntity();
if (entity != null) {
JsonValue jsonValue = Json.parse(EntityUtils.toString(entity));
if (jsonValue.isObject()) {
JsonObject jsonObject = jsonValue.asObject();
return jsonObject.get("rest").asString();
}
}
}
return null;
}
private static JsonValue urlGetJson(String getUrl) {
try {
String proxyAddress = Configuration.updateProxyAddress.get();
URL url = new URL(getUrl);
URLConnection uc;
if (proxyAddress != null && !proxyAddress.isEmpty()) {
int port = 8080;
if (proxyAddress.contains(":")) {
String[] parts = proxyAddress.split(":");
port = Integer.parseInt(parts[1]);
proxyAddress = parts[0];
}
uc = url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, port)));
} else {
uc = url.openConnection();
}
uc.setRequestProperty("User-Agent", ApplicationInfo.shortApplicationVerName);
uc.connect();
JsonValue value = Json.parse(new InputStreamReader(uc.getInputStream()));
return value;
} catch (IOException | NumberFormatException ex) {
return null;
}
}
private static Multimap<JsonStage, JsonValue> load(Map<String, FileHandle> map) throws IOException {
Multimap<JsonStage, JsonValue> m = new Multimap<JsonStage, JsonValue>();
for (Map.Entry<String, FileHandle> entry : map.entrySet()) {
JsonStage stage = null;
if (entry.getKey().startsWith("block")) {
stage = JsonStage.BLOCK;
} else if (entry.getKey().startsWith("item")) {
stage = JsonStage.ITEM;
} else if (entry.getKey().startsWith("recipe")) {
stage = JsonStage.RECIPE;
} else {
throw new CubesException("Invalid json file path \"" + entry.getKey() + "\"");
}
Reader reader = entry.getValue().reader();
try {
m.put(stage, Json.parse(reader));
} finally {
reader.close();
}
}
return m;
}
/**
* Tests GET of a single Load statistics object.
*/
@Test
public void testSingleLoadGet() throws UnsupportedEncodingException {
final WebTarget wt = target();
final String response = wt.path("statistics/flows/link")
.queryParam("device", "of:0000000000000001")
.queryParam("port", "2")
.request()
.get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("loads"));
final JsonArray jsonLoads = result.get("loads").asArray();
assertThat(jsonLoads, notNullValue());
assertThat(jsonLoads.size(), is(1));
JsonObject load1 = jsonLoads.get(0).asObject();
checkValues(load1, 111, 222, true, "src3");
}
/**
* Tests the result of the rest api GET with a device ID when there are
* active mappings.
*/
@Test
public void testMappingsByDevIdPopulateArray() {
setupMockMappings();
expect(mockDeviceService.getDevice(deviceId2)).andReturn(device2);
expect(mockMappingService.getMappingEntries(MAP_DATABASE, deviceId2))
.andReturn(mappings.get(deviceId2)).once();
replay(mockDeviceService);
replay(mockMappingService);
final WebTarget wt = target();
final String response = wt.path(PREFIX + "/" + deviceId2 + "/" + DATABASE)
.request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("mappings"));
final JsonArray jsonMappings = result.get("mappings").asArray();
assertThat(jsonMappings, notNullValue());
assertThat(jsonMappings, hasMapping(mapping3));
assertThat(jsonMappings, hasMapping(mapping4));
}
/**
* Tests the result of the rest api GET for OFAgent.
*
* @throws IOException IO exception
*/
@Test
public void testOFAgent() throws IOException {
expect(mockOFAgentService.agent(eq(NETWORK))).andReturn(OF_AGENT).anyTimes();
replay(mockOFAgentService);
final WebTarget wt = target();
assertNotNull("WebTarget is null", wt);
assertNotNull("WebTarget request is null", wt.request());
final Response response = wt.path("service/ofagent/" + NETWORK).request().get();
final JsonObject result = Json.parse(response.readEntity(String.class)).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(4));
assertThat(result.get("networkId").asString(), is(NETWORK.id().toString()));
assertThat(result.get("tenantId").asString(), is(TENANT.id()));
assertThat(result.get("state").asString(), is(STOPPED.toString()));
verify(mockOFAgentService);
}
/**
* Tests the results of a rest api GET for a device.
*/
@Test
public void testMeterSingleDevice() {
setupMockMeters();
final Set<Meter> meters1 = new HashSet<>();
meters1.add(meter1);
meters1.add(meter2);
expect(mockMeterService.getMeters(anyObject())).andReturn(meters1).anyTimes();
replay(mockMeterService);
replay(mockDeviceService);
final WebTarget wt = target();
final String response = wt.path("meters/" + deviceId1.toString()).request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("meters"));
final JsonArray jsonMeters = result.get("meters").asArray();
assertThat(jsonMeters, notNullValue());
assertThat(jsonMeters, hasMeter(meter1));
assertThat(jsonMeters, hasMeter(meter2));
}
/**
* Tests fetch of one host by Id.
*/
@Test
public void testSingleHostByIdFetch() {
final ProviderId pid = new ProviderId("of", "foo");
final MacAddress mac1 = MacAddress.valueOf("00:00:11:00:00:01");
final Set<IpAddress> ips1 = ImmutableSet.of(IpAddress.valueOf("1111:1111:1111:1::"));
final Host host1 =
new DefaultHost(pid, HostId.hostId(mac1), valueOf(1), vlanId((short) 1),
new HostLocation(DeviceId.deviceId("1"), portNumber(11), 1),
ips1);
hosts.add(host1);
expect(mockHostService.getHost(HostId.hostId("00:00:11:00:00:01/1")))
.andReturn(host1)
.anyTimes();
replay(mockHostService);
WebTarget wt = target();
String response = wt.path("hosts/00:00:11:00:00:01%2F1").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, matchesHost(host1));
}
/**
* Tests obtaining a global unique nextId with GET.
*/
@Test
public void testNextId() {
expect(mockFlowObjectiveService.allocateNextId()).andReturn(10).anyTimes();
prepareService();
WebTarget wt = target();
final String response = wt.path("flowobjectives/next").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("nextId"));
final int jsonNextId = result.get("nextId").asInt();
assertThat(jsonNextId, is(10));
}
/**
* Tests the result of the rest api GET when there are active meters.
*/
@Test
public void testMetersPopulatedArray() {
setupMockMeters();
replay(mockMeterService);
replay(mockDeviceService);
final WebTarget wt = target();
final String response = wt.path("meters").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("meters"));
final JsonArray jsonMeters = result.get("meters").asArray();
assertThat(jsonMeters, notNullValue());
assertThat(jsonMeters, hasMeter(meter1));
assertThat(jsonMeters, hasMeter(meter2));
assertThat(jsonMeters, hasMeter(meter3));
assertThat(jsonMeters, hasMeter(meter4));
}
/**
* Tests the result of the REST API GET when virtual networks are defined.
*/
@Test
public void testGetVirtualNetworksArray() {
final Set<VirtualNetwork> vnetSet = ImmutableSet.of(vnet1, vnet2, vnet3, vnet4);
expect(mockVnetAdminService.getTenantIds()).andReturn(ImmutableSet.of(tenantId3)).anyTimes();
replay(mockVnetAdminService);
expect(mockVnetService.getVirtualNetworks(tenantId3)).andReturn(vnetSet).anyTimes();
replay(mockVnetService);
WebTarget wt = target();
String response = wt.path("vnets").request().get(String.class);
assertThat(response, containsString("{\"vnets\":["));
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("vnets"));
final JsonArray vnetJsonArray = result.get("vnets").asArray();
assertThat(vnetJsonArray, notNullValue());
assertEquals("Virtual networks array is not the correct size.",
vnetSet.size(), vnetJsonArray.size());
vnetSet.forEach(vnet -> assertThat(vnetJsonArray, hasVnet(vnet)));
verify(mockVnetService);
verify(mockVnetAdminService);
}
/**
* Tests the result of the rest api GET when intents are defined.
*/
@Test
public void testIntentsArray() {
replay(mockIntentService);
final Intent intent1 = new MockIntent(1L, Collections.emptyList());
final HashSet<NetworkResource> resources = new HashSet<>();
resources.add(new MockResource(1));
resources.add(new MockResource(2));
resources.add(new MockResource(3));
final Intent intent2 = new MockIntent(2L, resources);
intents.add(intent1);
intents.add(intent2);
final WebTarget wt = target();
final String response = wt.path("intents").request().get(String.class);
assertThat(response, containsString("{\"intents\":["));
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("intents"));
final JsonArray jsonIntents = result.get("intents").asArray();
assertThat(jsonIntents, notNullValue());
assertThat(jsonIntents, hasIntent(intent1));
assertThat(jsonIntents, hasIntent(intent2));
}
public static JsonObject parseJsonObject(String json)
throws IOException
{
try
{
return Json.parse(json).asObject();
} catch (RuntimeException rte)
{
throw new IOException(rte);
}
}
public static ModelAndView doLogin(Authenticator auth, String username, String password) {
String token = auth.authenticate(username, password);
ModelAndView result = new ModelAndView();
if (token == null) {
result.setData(new ValidationResult("Invalid login or password").toJson());
result.setStatus(Response.Status.UNAUTHORIZED);
} else {
JsonObject data = Json.object();
data.add("access_token", token);
data.add("token_type", "bearer");
data.add("expires_in", auth.getMaxAgeMillis() / 1000);
result.setData(data.toString());
}
return result;
}
private static ModelAndView processPost(IHTTPSession session, HttpContoller controller) {
ModelAndView model;
JsonValue request;
try {
request = Json.parse(WebServer.getRequestBody(session));
if (!request.isObject()) {
model = new BadRequest("expected object");
} else {
model = controller.doPost(request.asObject());
}
} catch (ParseException e) {
model = new BadRequest("expected json object");
}
return model;
}
public String toJson() {
JsonObject result = Json.object();
if (!isEmpty()) {
JsonObject errors = Json.object();
if (general != null) {
errors.add("general", general);
}
for (Entry<String, String> cur : entrySet()) {
errors.add(cur.getKey(), cur.getValue());
}
result.add("errors", errors);
}
return result.toString();
}
@Before
public void setUp() throws Exception {
runner = JsonRunnerFactory.findByName(name);
json = readResource("input/test.json");
jsonBytes = json.getBytes(JsonRunner.UTF8);
minimalJsonModel = Json.parse(json);
}
public static void assertJson(String classPathResource, JsonObject actual) {
assertNotNull(actual);
try (Reader is = new InputStreamReader(TestUtil.class.getClassLoader().getResourceAsStream(classPathResource), StandardCharsets.UTF_8)) {
JsonValue value = Json.parse(is);
assertTrue(value.isObject());
assertJson(value.asObject(), actual);
} catch (Exception e) {
fail("unable to assert json: " + classPathResource + " " + e.getMessage());
}
}
/**
* Tests a GET of a single application.
*/
@Test
public void getSingleApplication() {
replay(appService);
WebTarget wt = target();
String response = wt.path("applications/three").request().get(String.class);
JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result, matchesApp(app3));
verify(appService);
}
public String scheduleStart(String satelliteId) {
HttpResponse<String> response = scheduleStartResponse(satelliteId);
if (response.statusCode() != 200) {
LOG.info("response: {}", response.body());
throw new RuntimeException("invalid status code: " + response.statusCode());
}
JsonObject json = (JsonObject) Json.parse(response.body());
return json.getString("id", null);
}
/**
* Tests the result of the REST API GET when virtual links are defined.
*/
@Test
public void testGetVirtualLinksArray() {
NetworkId networkId = networkId3;
final Set<VirtualLink> vlinkSet = ImmutableSet.of(vlink1, vlink2);
expect(mockVnetService.getVirtualLinks(networkId)).andReturn(vlinkSet).anyTimes();
replay(mockVnetService);
WebTarget wt = target();
String location = "vnets/" + networkId.toString() + "/links";
String response = wt.path(location).request().get(String.class);
assertThat(response, containsString("{\"links\":["));
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names(), hasSize(1));
assertThat(result.names().get(0), is("links"));
final JsonArray vnetJsonArray = result.get("links").asArray();
assertThat(vnetJsonArray, notNullValue());
assertEquals("Virtual links array is not the correct size.",
vlinkSet.size(), vnetJsonArray.size());
vlinkSet.forEach(vlink -> assertThat(vnetJsonArray, hasVlink(vlink)));
verify(mockVnetService);
}
/**
* Tests the result of a rest api GET for port chain id.
*/
@Test
public void testGetPortChainDeviceMap() {
expect(portChainService.getPortChain(anyObject())).andReturn(portChain1).anyTimes();
replay(portChainService);
final WebTarget wt = target();
final String response = wt.path("portChainDeviceMap/1278dcd4-459f-62ed-754b-87fc5e4a6751").request()
.get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
assertThat(result.names().get(0), is("portChainDeviceMap"));
}