@Test(dependsOnMethods = {"testDeployApplication", "testLocatedLocation"}) public void testDeployApplicationFromBuilder() throws Exception { ApplicationSpec spec = ApplicationSpec.builder() .type(RestMockAppBuilder.class.getCanonicalName()) .name("simple-app-builder") .locations(ImmutableSet.of("localhost")) .build(); ClientResponse response = clientDeploy(spec); assertTrue(response.getStatus() / 100 == 2, "response is " + response); // Expect app to be running URI appUri = response.getLocation(); waitForApplicationToBeRunning(response.getLocation(), Duration.TEN_SECONDS); assertEquals( client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-builder"); // Expect app to have the child-entity Set<EntitySummary> entities = client() .resource(appUri.toString() + "/entities") .get(new GenericType<Set<EntitySummary>>() {}); assertEquals(entities.size(), 1); assertEquals(Iterables.getOnlyElement(entities).getName(), "child1"); assertEquals( Iterables.getOnlyElement(entities).getType(), RestMockSimpleEntity.class.getCanonicalName()); }
@Override public ListenableFuture<RpcResult<Void>> startListening() { ClientResponse response = null; try { response = extractWebSocketUriFromRpc(this.streamInfo.getIdentifier()); } catch (ExecutionException e) { logger.trace("Execution exception while extracting stream name {}", e); throw new IllegalStateException(e); } catch (InterruptedException e) { logger.trace("InterruptedException while extracting stream name {}", e); throw new IllegalStateException(e); } catch (UnsupportedEncodingException e) { logger.trace("UnsupportedEncodingException while extracting stream name {}", e); throw new IllegalStateException(e); } boolean success = true; if (response.getStatus() != STATUS_OK) { success = false; } final RestRpcResult rpcResult = new RestRpcResult(success, response.getLocation()); createWebsocketClient(response.getLocation()); ListenableFuture<RpcResult<Void>> future = pool.submit( new Callable<RpcResult<Void>>() { @Override public RpcResult<Void> call() { return rpcResult; } }); return future; }
@SuppressWarnings("deprecation") @Test public void testReferenceCatalogEntity() throws Exception { getManagementContext().getCatalog().addItem(BasicEntity.class); String yaml = "{ name: simple-app-yaml, location: localhost, services: [ { serviceType: " + BasicEntity.class.getName() + " } ] }"; ClientResponse response = client() .resource("/v1/applications") .entity(yaml, "application/x-yaml") .post(ClientResponse.class); assertTrue(response.getStatus() / 100 == 2, "response is " + response); // Expect app to be running URI appUri = response.getLocation(); waitForApplicationToBeRunning(response.getLocation()); assertEquals( client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-yaml"); ClientResponse response2 = client().resource(appUri.getPath()).delete(ClientResponse.class); assertEquals(response2.getStatus(), Response.Status.ACCEPTED.getStatusCode()); }
protected T get(URI uri) { ClientResponse response = ClientUtil.readEntity( uri, getHttpClient(), getResourceRepresentationType(), ClientResponse.class); if (logger.isDebugEnabled()) { logger.debug("Request Accept header: " + getResourceRepresentationType()); logger.debug("Response header: " + response.getType()); } final int status = response.getStatus(); if (followRedirectionEnabled && status == ClientResponse.Status.MOVED_PERMANENTLY.getStatusCode()) { final URI location = response.getLocation(); if (location != null) { this.thisResourceUri = location; this.absoluteThisResourceUri = generateAbsoluteUri(); return get(); } } if (followRedirectionEnabled && (status == ClientResponse.Status.FOUND.getStatusCode() || status == ClientResponse.Status.SEE_OTHER.getStatusCode())) { final URI location = response.getLocation(); if (location != null) { URI absolutionLocation = getHttpClient().getAbsoluteUri(location, getReferrerUri()); return get(absolutionLocation); } } if (status < 300 || (status == ClientResponse.Status.NOT_MODIFIED.getStatusCode())) { if (response.hasEntity() && response.getStatus() != ClientResponse.Status.NO_CONTENT.getStatusCode()) { lastReadStateOfEntity = response.getEntity(getEntityClass()); if (getClientUtil() != null) { try { getClientUtil().parseLinks(lastReadStateOfEntity, getRelatedResourceUris()); } catch (Exception ex) { logger.warn(ex.getMessage(), ex); } } if (invokeGet) { invokeGETOnNestedResources(); } } else { lastReadStateOfEntity = null; } getInvocationCount++; Map<String, Object> headers = new HashMap<String, Object>(); EntityTag tag = response.getEntityTag(); if (tag != null) { headers.put(HttpHeaders.ETAG, tag); } Date date = response.getLastModified(); if (date != null) { headers.put(HttpHeaders.LAST_MODIFIED, date); } cachedHeaders.put(uri.toString(), headers); return lastReadStateOfEntity; } throw new UniformInterfaceException(response); }
@Test public void testDeployApplication() throws Exception { ClientResponse response = clientDeploy(simpleSpec); HttpTestUtils.assertHealthyStatusCode(response.getStatus()); assertEquals(getManagementContext().getApplications().size(), 1); assertRegexMatches(response.getLocation().getPath(), "/v1/applications/.*"); // Object taskO = response.getEntity(Object.class); TaskSummary task = response.getEntity(TaskSummary.class); log.info("deployed, got " + task); assertEquals( task.getEntityId(), getManagementContext().getApplications().iterator().next().getApplicationId()); waitForApplicationToBeRunning(response.getLocation()); }
// @Test public void testSubnetCascadingDelete() { // Create a subnet with several configuration pieces: option 3, // option 121, and a host assignment. Then delete it. ClientResponse response; DtoDhcpSubnet subnet = new DtoDhcpSubnet(); subnet.setSubnetPrefix("172.31.0.0"); subnet.setSubnetLength(24); subnet.setServerAddr("172.31.0.118"); response = resource() .uri(bridge.getDhcpSubnets()) .type(APPLICATION_DHCP_SUBNET_JSON) .post(ClientResponse.class, subnet); assertEquals(201, response.getStatus()); subnet = resource() .uri(response.getLocation()) .accept(APPLICATION_DHCP_SUBNET_JSON) .get(DtoDhcpSubnet.class); DtoDhcpHost host1 = new DtoDhcpHost(); host1.setMacAddr("02:33:44:55:00:00"); host1.setIpAddr("172.31.0.11"); host1.setName("saturn"); response = resource() .uri(subnet.getHosts()) .type(APPLICATION_DHCP_HOST_JSON) .post(ClientResponse.class, host1); assertEquals(201, response.getStatus()); // List the subnets response = resource() .uri(bridge.getDhcpSubnets()) .accept(APPLICATION_DHCP_SUBNET_COLLECTION_JSON) .get(ClientResponse.class); assertEquals(200, response.getStatus()); DtoDhcpSubnet[] subnets = response.getEntity(DtoDhcpSubnet[].class); assertThat("We expect 1 listed subnets.", subnets, arrayWithSize(1)); assertThat( "We expect the listed subnets to match the one we created.", subnets, arrayContainingInAnyOrder(subnet)); // Now delete the subnet. response = resource().uri(subnet.getUri()).delete(ClientResponse.class); assertEquals(204, response.getStatus()); // Show that the list of DHCP subnet configurations is empty. response = resource() .uri(bridge.getDhcpSubnets()) .accept(APPLICATION_DHCP_SUBNET_COLLECTION_JSON) .get(ClientResponse.class); assertEquals(200, response.getStatus()); subnets = response.getEntity(DtoDhcpSubnet[].class); assertThat("We expect 0 listed subnets.", subnets, arrayWithSize(0)); }
public URI put(URI uri, Object entity, String mediaType) { ClientResponse response = resource().uri(uri).type(mediaType).put(ClientResponse.class, entity); if (response.getStatus() != 204 && response.getStatus() != 200) { handleHttpError(response); } return response.getLocation(); }
private REST handle(ClientResponse response) { status = response.getStatus(); location = response.getLocation(); readEntityIfPossible(response); response.close(); System.out.printf( "GET from [%s], status code [%d] location: %s, returned data: %n%s", path, status, location, entity); return this; }
@Test(dependsOnMethods = {"testDeployApplication", "testLocatedLocation"}) public void testDeployApplicationFromInterface() throws Exception { ApplicationSpec spec = ApplicationSpec.builder() .type(BasicApplication.class.getCanonicalName()) .name("simple-app-interface") .locations(ImmutableSet.of("localhost")) .build(); ClientResponse response = clientDeploy(spec); assertTrue(response.getStatus() / 100 == 2, "response is " + response); // Expect app to be running URI appUri = response.getLocation(); waitForApplicationToBeRunning(response.getLocation()); assertEquals( client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-interface"); }
@Test(dependsOnMethods = {"testDeleteApplication"}) // this must happen after we've deleted the main application, as testLocatedLocations assumes a // single location public void testDeployApplicationImpl() throws Exception { ApplicationSpec spec = ApplicationSpec.builder() .type(RestMockApp.class.getCanonicalName()) .name("simple-app-impl") .locations(ImmutableSet.of("localhost")) .build(); ClientResponse response = clientDeploy(spec); assertTrue(response.getStatus() / 100 == 2, "response is " + response); // Expect app to be running URI appUri = response.getLocation(); waitForApplicationToBeRunning(response.getLocation()); assertEquals( client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-impl"); }
@Test(dependsOnMethods = {"testDeployApplication", "testLocatedLocation"}) public void testDeployApplicationYaml() throws Exception { String yaml = "{ name: simple-app-yaml, location: localhost, services: [ { serviceType: " + BasicApplication.class.getCanonicalName() + " } ] }"; ClientResponse response = client() .resource("/v1/applications") .entity(yaml, "application/x-yaml") .post(ClientResponse.class); assertTrue(response.getStatus() / 100 == 2, "response is " + response); // Expect app to be running URI appUri = response.getLocation(); waitForApplicationToBeRunning(response.getLocation()); assertEquals( client().resource(appUri).get(ApplicationSummary.class).getSpec().getName(), "simple-app-yaml"); }
@Test public void testTryingToAddInvalidResearcherUrls() throws InterruptedException, JSONException, URISyntaxException { String accessToken = getAccessToken(this.client1ClientId, this.client1ClientSecret, this.client1RedirectUri); assertNotNull(accessToken); ResearcherUrl rUrlToCreate = new ResearcherUrl(); rUrlToCreate.setUrl(new Url("")); rUrlToCreate.setUrlName(""); // Create ClientResponse postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken); assertNotNull(postResponse); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), postResponse.getStatus()); String _351Chars = new String(); for (int i = 0; i < 531; i++) { _351Chars += "a"; } rUrlToCreate.setUrl(new Url(_351Chars)); postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken); assertNotNull(postResponse); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), postResponse.getStatus()); rUrlToCreate.setUrl(new Url("http://myurl.com")); rUrlToCreate.setUrlName(_351Chars); postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken); assertNotNull(postResponse); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), postResponse.getStatus()); rUrlToCreate.setUrlName("The name"); postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken); assertNotNull(postResponse); assertEquals(Response.Status.CREATED.getStatusCode(), postResponse.getStatus()); // Read it to delete it ClientResponse getResponse = memberV2ApiClient.viewLocationXml(postResponse.getLocation(), accessToken); assertEquals(Response.Status.OK.getStatusCode(), getResponse.getStatus()); ResearcherUrl gotResearcherUrl = getResponse.getEntity(ResearcherUrl.class); ClientResponse deleteResponse = memberV2ApiClient.deleteResearcherUrl( this.user1OrcidId, gotResearcherUrl.getPutCode(), accessToken); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), deleteResponse.getStatus()); }
/* * Handle request redirects, adding cookies and setting the redirect URL */ private WebResource handelRedirect(ClientResponse response) { URI url = response.getLocation(); List<NewCookie> cookies = response.getCookies(); if (cookies != null && !cookies.isEmpty()) { _requestCookies.addAll(cookies); } else { _logger.debug("no cookies"); } if (url != null) { _logger.debug("redirected url: {}", url.toString()); WebResource resource = _client.getResource(url.toString()); return resource; } else { _logger.error("Could not find redirected url"); return null; } }
@Before public void before() { ClientResponse response; DtoApplication app = resource().path("").accept(APPLICATION_JSON_V5).get(DtoApplication.class); bridge = new DtoBridge(); bridge.setName("br1234"); bridge.setTenantId("DhcpTenant"); response = resource() .uri(app.getBridges()) .type(APPLICATION_BRIDGE_JSON) .post(ClientResponse.class, bridge); assertEquals("The bridge was created.", 201, response.getStatus()); bridge = resource().uri(response.getLocation()).accept(APPLICATION_BRIDGE_JSON).get(DtoBridge.class); }
public String createVM(String service_id, ServiceComponent sc, int index) throws ServiceInstantiationException { WebResource r = client.resource(base_url + "/optimis_compute"); try { ClientResponse res = r.type(MediaType.APPLICATION_JSON_TYPE) .post(ClientResponse.class, renderCompute(service_id, sc, index)); if (res.getStatus() != Status.CREATED.getStatusCode()) { throw new ServiceInstantiationException( "There was a problem while processing the request: " + res.getStatus(), new Exception()); } // return res.getHeaders().get(HttpHeaders.LOCATION).get(0); return res.getLocation().toString(); } catch (JSONEncodingException e) { throw new ServiceInstantiationException( "There was a problem when transforming the service component to JSON format", e); } }
private static URI sendNodeToServer() { final String nodeEntryPointUri = SERVER_ROOT_URI + "node"; // http://localhost:7474/db/data/node WebResource resource = Client.create().resource(nodeEntryPointUri); // POST {} to the node entry point URI ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .entity("{}") .post(ClientResponse.class); URI location = response.getLocation(); System.out.println( String.format("POST to [%s], status code [%d]", nodeEntryPointUri, response.getStatus())); response.close(); return location; }
@Test public void testEnabled() { ClientResponse response; // Create an enabled subnet DtoDhcpSubnet subnet1 = new DtoDhcpSubnet(); subnet1.setSubnetPrefix("10.0.0.0"); subnet1.setSubnetLength(24); response = resource() .uri(bridge.getDhcpSubnets()) .type(APPLICATION_DHCP_SUBNET_JSON_V2) .post(ClientResponse.class, subnet1); assertEquals(201, response.getStatus()); // Test GET subnet1 = resource() .uri(response.getLocation()) .accept(APPLICATION_DHCP_SUBNET_JSON_V2) .get(DtoDhcpSubnet.class); assertEquals(true, subnet1.isEnabled()); // Disable a subnet via update subnet1.setEnabled(false); response = resource() .uri(subnet1.getUri()) .type(APPLICATION_DHCP_SUBNET_JSON_V2) .put(ClientResponse.class, subnet1); assertEquals(204, response.getStatus()); subnet1 = resource() .uri(subnet1.getUri()) .accept(APPLICATION_DHCP_SUBNET_JSON_V2) .get(DtoDhcpSubnet.class); assertEquals(false, subnet1.isEnabled()); }
OrganizationsResourceImpl(Link orgsLink) { this.orgsLink = orgsLink; orgsURI = UriBuilder.fromUri(BASE_URI.toString() + orgsLink.getHref().toString()).build(); URI uri = UriBuilder.fromUri(BASE_URI.toString() + orgsLink.getHref().toString()).build(); ClientResponse response = ClientUtil.readClientResponse(uri, getHttpClient(), MediaType.APPLICATION_ATOM_XML); PaginatedFeedEntitiesList<Organization> pgs; if (response.getStatus() == 200) { Feed feed = ClientUtil.getFeed(response); entries = feed.getEntries(); orgsLink = feed.getLink(REL_ORG); if (response.getHeaders().getFirst("Cache-Control") != null) isCacheEnabled = response.getHeaders().getFirst("Cache-Control").equals("no-cache"); String dateString = response.getHeaders().getFirst("Last-Modified"); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); try { lastModifiedDate = format.parse(dateString); } catch (Exception ex) { } dateString = response.getHeaders().getFirst("Expires"); try { lastModifiedDate = format.parse(dateString); } catch (Exception ex) { } uri = response.getLocation(); } else { orgLink = null; } }
private static URI addRelationship( URI startNode, URI endNode, String relationshipType, String jsonAttributes) throws URISyntaxException { URI fromUri = new URI(startNode.toString() + "/relationships"); String relationshipJson = generateJsonRelationship(endNode, relationshipType, jsonAttributes); System.out.println(relationshipJson + "==================================="); WebResource resource = Client.create().resource(fromUri); // POST JSON to the relationships URI ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .entity(relationshipJson) .post(ClientResponse.class); final URI location = response.getLocation(); System.out.println( String.format( "POST to [%s], status code [%d], location header [%s]", fromUri, response.getStatus(), location.toString())); response.close(); return location; }
private static void setRelationshipServer(String node1, String node2, String type) { URI fromUri = null; try { fromUri = new URI("http://localhost:7474/db/data/node/" + node1 + "/relationships/"); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String endUri = "http://localhost:7474/db/data/node/" + node2; String relationshipJson = generateJsonRelationship(endUri, type, "rel"); WebResource resource = Client.create().resource(fromUri); // POST JSON to the relationships URI ClientResponse response = resource .accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_JSON) .entity(relationshipJson) .post(ClientResponse.class); final URI location = response.getLocation(); System.out.println( String.format("POST to [%s], status code [%d]", fromUri, response.getStatus())); response.close(); }
@Test public void testResearcherUrl() throws InterruptedException, JSONException, URISyntaxException { String accessToken = getAccessToken(this.client1ClientId, this.client1ClientSecret, this.client1RedirectUri); assertNotNull(accessToken); ResearcherUrl rUrlToCreate = (ResearcherUrl) unmarshallFromPath( "/record_2.0_rc2/samples/researcher-url-2.0_rc2.xml", ResearcherUrl.class); assertNotNull(rUrlToCreate); Long time = System.currentTimeMillis(); rUrlToCreate.setCreatedDate(null); rUrlToCreate.setLastModifiedDate(null); rUrlToCreate.setPath(null); rUrlToCreate.setPutCode(null); rUrlToCreate.setSource(null); rUrlToCreate.setUrl(new Url(rUrlToCreate.getUrl().getValue() + time)); rUrlToCreate.setUrlName(String.valueOf(time)); // Create ClientResponse postResponse = memberV2ApiClient.createResearcherUrls(user1OrcidId, rUrlToCreate, accessToken); assertNotNull(postResponse); assertEquals(Response.Status.CREATED.getStatusCode(), postResponse.getStatus()); String locationPath = postResponse.getLocation().getPath(); assertTrue( "Location header path should match pattern, but was " + locationPath, locationPath.matches(".*/v2.0_rc2/" + user1OrcidId + "/researcher-urls/\\d+")); // Read ClientResponse getResponse = memberV2ApiClient.viewLocationXml(postResponse.getLocation(), accessToken); assertEquals(Response.Status.OK.getStatusCode(), getResponse.getStatus()); ResearcherUrl gotResearcherUrl = getResponse.getEntity(ResearcherUrl.class); assertNotNull(gotResearcherUrl); assertNotNull(gotResearcherUrl.getPutCode()); assertNotNull(gotResearcherUrl.getSource()); assertNotNull(gotResearcherUrl.getCreatedDate()); assertNotNull(gotResearcherUrl.getLastModifiedDate()); assertEquals(this.client1ClientId, gotResearcherUrl.getSource().retrieveSourcePath()); assertEquals("http://site1.com/" + time, gotResearcherUrl.getUrl().getValue()); assertEquals(String.valueOf(time), gotResearcherUrl.getUrlName()); assertEquals("public", gotResearcherUrl.getVisibility().value()); // Update LastModifiedDate initialLastModified = gotResearcherUrl.getLastModifiedDate(); Long currentTime = System.currentTimeMillis(); gotResearcherUrl.setUrlName(gotResearcherUrl.getUrlName() + " - " + currentTime); gotResearcherUrl.getUrl().setValue(gotResearcherUrl.getUrl().getValue() + currentTime); gotResearcherUrl.setVisibility(Visibility.LIMITED); ClientResponse updatedResearcherUrlResponse = memberV2ApiClient.updateResearcherUrls(this.user1OrcidId, gotResearcherUrl, accessToken); assertNotNull(updatedResearcherUrlResponse); assertEquals(Response.Status.OK.getStatusCode(), updatedResearcherUrlResponse.getStatus()); ResearcherUrl updatedResearcherUrl = updatedResearcherUrlResponse.getEntity(ResearcherUrl.class); assertNotNull(updatedResearcherUrl); assertEquals( "http://site1.com/" + time + currentTime, updatedResearcherUrl.getUrl().getValue()); assertEquals(String.valueOf(time) + " - " + currentTime, updatedResearcherUrl.getUrlName()); // Keep it public, since it is more restrictive than the user visibility // default assertEquals("public", updatedResearcherUrl.getVisibility().value()); assertFalse(initialLastModified.equals(updatedResearcherUrl.getLastModifiedDate())); // Delete ClientResponse deleteResponse = memberV2ApiClient.deleteResearcherUrl( this.user1OrcidId, gotResearcherUrl.getPutCode(), accessToken); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), deleteResponse.getStatus()); }
// @Test public void testSubnetCreateGetListDelete() { ClientResponse response; // Create a subnet DtoDhcpSubnet subnet1 = new DtoDhcpSubnet(); subnet1.setSubnetPrefix("172.31.0.0"); subnet1.setSubnetLength(24); subnet1.setServerAddr("172.31.0.118"); response = resource() .uri(bridge.getDhcpSubnets()) .type(APPLICATION_DHCP_SUBNET_JSON) .post(ClientResponse.class, subnet1); assertEquals(201, response.getStatus()); // Test GET subnet1 = resource() .uri(response.getLocation()) .accept(APPLICATION_DHCP_SUBNET_JSON) .get(DtoDhcpSubnet.class); assertEquals("172.31.0.0", subnet1.getSubnetPrefix()); assertEquals(24, subnet1.getSubnetLength()); // Create another subnet DtoDhcpSubnet subnet2 = new DtoDhcpSubnet(); subnet2.setSubnetPrefix("172.31.1.0"); subnet2.setSubnetLength(24); subnet2.setServerAddr("172.31.1.118"); response = resource() .uri(bridge.getDhcpSubnets()) .type(APPLICATION_DHCP_SUBNET_JSON) .post(ClientResponse.class, subnet2); assertEquals(201, response.getStatus()); subnet2 = resource() .uri(response.getLocation()) .accept(APPLICATION_DHCP_SUBNET_JSON) .get(DtoDhcpSubnet.class); assertEquals("172.31.1.0", subnet2.getSubnetPrefix()); assertEquals(24, subnet2.getSubnetLength()); // List the subnets response = resource() .uri(bridge.getDhcpSubnets()) .accept(APPLICATION_DHCP_SUBNET_COLLECTION_JSON) .get(ClientResponse.class); assertEquals(200, response.getStatus()); DtoDhcpSubnet[] subnets = response.getEntity(DtoDhcpSubnet[].class); assertThat("We expect 2 listed subnets.", subnets, arrayWithSize(2)); assertThat( "We expect the listed subnets to match those we created.", subnets, arrayContainingInAnyOrder(subnet1, subnet2)); // Delete the first subnet response = resource().uri(subnet1.getUri()).delete(ClientResponse.class); assertEquals(204, response.getStatus()); // There should now be only the second subnet. response = resource() .uri(bridge.getDhcpSubnets()) .accept(APPLICATION_DHCP_SUBNET_COLLECTION_JSON) .get(ClientResponse.class); assertEquals(200, response.getStatus()); subnets = response.getEntity(DtoDhcpSubnet[].class); assertThat("We expect 1 listed subnet after the delete", subnets, arrayWithSize(1)); assertThat( "The listed subnet should be the one that wasn't deleted.", subnets, arrayContainingInAnyOrder(subnet2)); // Test GET of a non-existing subnet (the deleted first subnet). response = resource() .uri(subnet1.getUri()) .accept(APPLICATION_DHCP_SUBNET_JSON) .get(ClientResponse.class); assertEquals(404, response.getStatus()); }
@Test public void testDhcpRoutes() { ClientResponse response; DtoDhcpSubnet subnet1 = new DtoDhcpSubnet(); subnet1.setSubnetPrefix("172.0.0.0"); subnet1.setSubnetLength(24); subnet1.setDefaultGateway("172.0.0.254"); subnet1.setServerAddr("172.0.0.118"); subnet1.getOpt121Routes().add(new DtoDhcpOption121("172.31.1.0", 24, "172.0.0.253")); subnet1.getOpt121Routes().add(new DtoDhcpOption121("172.31.2.0", 24, "172.0.0.253")); response = resource() .uri(bridge.getDhcpSubnets()) .type(APPLICATION_DHCP_SUBNET_JSON) .post(ClientResponse.class, subnet1); assertEquals(201, response.getStatus()); DtoDhcpSubnet subnet2 = resource() .uri(response.getLocation()) .accept(APPLICATION_DHCP_SUBNET_JSON) .get(DtoDhcpSubnet.class); // Copy the URIs from the GET to the DTO we used for create. subnet1.setHosts(subnet2.getHosts()); subnet1.setUri(subnet2.getUri()); // Now the DTOs should be identical. assertEquals( "The DhcpSubnet client dto from GET should be " + "identical to the one passed to create", subnet1, subnet2); // Now modify the routes and do an update. subnet1.getOpt121Routes().remove(0); subnet1.getOpt121Routes().add(new DtoDhcpOption121("172.31.3.0", 24, "172.0.0.252")); subnet1.getOpt121Routes().add(new DtoDhcpOption121("172.31.4.0", 24, "172.0.0.253")); subnet1.setDefaultGateway("172.0.0.1"); response = resource() .uri(subnet1.getUri()) .type(APPLICATION_DHCP_SUBNET_JSON) .put(ClientResponse.class, subnet1); assertEquals(204, response.getStatus()); subnet2 = resource() .uri(subnet1.getUri()) .accept(APPLICATION_DHCP_SUBNET_JSON) .get(DtoDhcpSubnet.class); // The URIs should not have changed, so the DTOs should be identical. assertEquals( "The DhcpSubnet client dto from GET should be " + "identical to the one passed to create", subnet1, subnet2); // Now try removing all routes. subnet1.getOpt121Routes().clear(); subnet1.setDefaultGateway(null); response = resource() .uri(subnet1.getUri()) .type(APPLICATION_DHCP_SUBNET_JSON) .put(ClientResponse.class, subnet1); assertEquals(204, response.getStatus()); subnet2 = resource() .uri(subnet1.getUri()) .accept(APPLICATION_DHCP_SUBNET_JSON) .get(DtoDhcpSubnet.class); // The URIs should not have changed, so the DTOs should be identical. assertEquals( "The DhcpSubnet client dto from GET should be " + "identical to the one passed to create", subnet1, subnet2); }
@Test public void testHosts() { // In this test remember that there will be multiple host definitions. // The system enforces that there is only one host def per mac address. ClientResponse response; DtoDhcpSubnet subnet = new DtoDhcpSubnet(); subnet.setSubnetPrefix("172.31.0.0"); subnet.setSubnetLength(24); subnet.setServerAddr("172.31.0.118"); response = resource() .uri(bridge.getDhcpSubnets()) .type(APPLICATION_DHCP_SUBNET_JSON) .post(ClientResponse.class, subnet); assertEquals(201, response.getStatus()); subnet = resource() .uri(response.getLocation()) .accept(APPLICATION_DHCP_SUBNET_JSON) .get(DtoDhcpSubnet.class); DtoDhcpHost host1 = new DtoDhcpHost(); List<DtoExtraDhcpOpt> opts = new ArrayList<>(); opts.add(new DtoExtraDhcpOpt("name1", "val1")); opts.add(new DtoExtraDhcpOpt("name2", "val2")); opts.add(new DtoExtraDhcpOpt("name3", "val3")); host1.setMacAddr("02:33:44:55:00:00"); host1.setIpAddr("172.31.0.11"); host1.setName("saturn"); host1.setExtraDhcpOpts(opts); response = resource() .uri(subnet.getHosts()) .type(APPLICATION_DHCP_HOST_JSON_V2) .post(ClientResponse.class, host1); assertEquals(201, response.getStatus()); host1 = resource() .uri(response.getLocation()) .accept(APPLICATION_DHCP_HOST_JSON_V2) .get(DtoDhcpHost.class); assertEquals("02:33:44:55:00:00", host1.getMacAddr()); assertEquals("172.31.0.11", host1.getIpAddr()); assertEquals("saturn", host1.getName()); assertEquals(opts, host1.getExtraDhcpOpts()); DtoDhcpHost host2 = new DtoDhcpHost(); host2.setMacAddr("02:33:44:55:00:01"); host2.setIpAddr("172.31.0.12"); host2.setName("jupiter"); List<DtoExtraDhcpOpt> opts2 = new ArrayList<>(); opts2.add(new DtoExtraDhcpOpt("name1", "val1")); opts2.add(new DtoExtraDhcpOpt("name2", "val2")); opts2.add(new DtoExtraDhcpOpt("name3", "val3")); host2.setExtraDhcpOpts(opts2); response = resource() .uri(subnet.getHosts()) .type(APPLICATION_DHCP_HOST_JSON_V2) .post(ClientResponse.class, host2); assertEquals(201, response.getStatus()); host2 = resource() .uri(response.getLocation()) .accept(APPLICATION_DHCP_HOST_JSON_V2) .get(DtoDhcpHost.class); assertEquals("02:33:44:55:00:01", host2.getMacAddr()); assertEquals("172.31.0.12", host2.getIpAddr()); assertEquals("jupiter", host2.getName()); assertEquals(opts, host2.getExtraDhcpOpts()); // Now list all the host static assignments. response = resource() .uri(subnet.getHosts()) .accept(APPLICATION_DHCP_HOST_COLLECTION_JSON_V2) .get(ClientResponse.class); assertEquals(200, response.getStatus()); DtoDhcpHost[] hosts = response.getEntity(DtoDhcpHost[].class); assertThat("We expect 2 listed hosts.", hosts, arrayWithSize(2)); assertThat( "We expect the listed hosts to match those we created.", hosts, arrayContainingInAnyOrder(host2, host1)); // Now try to create a new host with host1's mac address. This should // fail. host1.setIpAddr("172.31.0.13"); response = resource() .uri(subnet.getHosts()) .type(APPLICATION_DHCP_HOST_JSON_V2) .post(ClientResponse.class, host1); assertEquals(409, response.getStatus()); // Try again, this time using an UPDATE operation. response = resource() .uri(host1.getUri()) .type(APPLICATION_DHCP_HOST_JSON_V2) .put(ClientResponse.class, host1); assertEquals(204, response.getStatus()); host1 = resource().uri(host1.getUri()).accept(APPLICATION_DHCP_HOST_JSON_V2).get(DtoDhcpHost.class); assertEquals("02:33:44:55:00:00", host1.getMacAddr()); assertEquals("172.31.0.13", host1.getIpAddr()); assertEquals("saturn", host1.getName()); // There should still be exactly 2 host assignments. response = resource() .uri(subnet.getHosts()) .accept(APPLICATION_DHCP_HOST_COLLECTION_JSON_V2) .get(ClientResponse.class); assertEquals(200, response.getStatus()); hosts = response.getEntity(DtoDhcpHost[].class); assertThat("We expect 2 listed hosts.", hosts, arrayWithSize(2)); assertThat( "We expect the listed hosts to match those we created.", hosts, arrayContainingInAnyOrder(host1, host2)); // Now delete one of the host assignments. response = resource().uri(host1.getUri()).delete(ClientResponse.class); assertEquals(204, response.getStatus()); // There should now be only 1 host assignment. response = resource() .uri(subnet.getHosts()) .accept(APPLICATION_DHCP_HOST_COLLECTION_JSON_V2) .get(ClientResponse.class); assertEquals(200, response.getStatus()); hosts = response.getEntity(DtoDhcpHost[].class); assertThat("We expect 1 listed host after the delete", hosts, arrayWithSize(1)); assertThat( "The listed hosts should be the one that wasn't deleted.", hosts, arrayContainingInAnyOrder(host2)); }