Java Code Examples for org.apache.brooklyn.util.http.HttpTool#httpPost()

The following examples show how to use org.apache.brooklyn.util.http.HttpTool#httpPost() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BrooklynPropertiesSecurityFilterTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Integration","Broken"})
public void testInteractionOfSecurityFilterAndFormMapProvider() throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        Server server = useServerForTest(baseLauncher()
                .forceUseOfDefaultCatalogWithJavaClassPath(true)
                .withoutJsgui()
                .start());
        String appId = startAppAtNode(server);
        String entityId = getTestEntityInApp(server, appId);
        HttpClient client = HttpTool.httpClientBuilder()
                .uri(getBaseUriRest())
                .build();
        List<? extends NameValuePair> nvps = Lists.newArrayList(
                new BasicNameValuePair("arg", "bar"));
        String effector = String.format("/applications/%s/entities/%s/effectors/identityEffector", appId, entityId);
        HttpToolResponse response = HttpTool.httpPost(client, URI.create(getBaseUriRest() + effector),
                ImmutableMap.of(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType()),
                URLEncodedUtils.format(nvps, Charsets.UTF_8).getBytes());

        LOG.info("Effector response: {}", response.getContentAsString());
        assertTrue(HttpTool.isStatusCodeHealthy(response.getResponseCode()), "response code=" + response.getResponseCode());
    } finally {
        LOG.info("testInteractionOfSecurityFilterAndFormMapProvider complete in " + Time.makeTimeStringRounded(stopwatch));
    }
}
 
Example 2
Source File: BrooklynPropertiesSecurityFilterTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private String startAppAtNode(Server server) throws Exception {
    String blueprint = "name: TestApp\n" +
            "location: localhost\n" +
            "services:\n" +
            "- type: org.apache.brooklyn.test.entity.TestEntity";
    HttpClient client = HttpTool.httpClientBuilder()
            .uri(getBaseUriRest(server))
            .build();
    HttpToolResponse response = HttpTool.httpPost(client, URI.create(getBaseUriRest() + "applications"),
            ImmutableMap.of(HttpHeaders.CONTENT_TYPE, "application/x-yaml"),
            blueprint.getBytes());
    assertTrue(HttpTool.isStatusCodeHealthy(response.getResponseCode()), "error creating app. response code=" + response.getResponseCode());
    @SuppressWarnings("unchecked")
    Map<String, Object> body = new ObjectMapper().readValue(response.getContent(), HashMap.class);
    return (String) body.get("entityId");
}
 
Example 3
Source File: VaultExternalConfigSupplier.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected JsonObject apiPost(String path, ImmutableMap<String, String> headers, ImmutableMap<String, String> requestData) {
    try {
        String body = gson.toJson(requestData);
        String uri = Urls.mergePaths(endpoint, path);
        LOG.trace("Vault request - POST: {}", uri);
        HttpToolResponse response = HttpTool.httpPost(httpClient, Urls.toUri(uri), headers, body.getBytes(CHARSET_NAME));
        LOG.trace("Vault response - code: {} {}", response.getResponseCode(), response.getReasonPhrase());
        String responseBody = new String(response.getContent(), CHARSET_NAME);
        if (HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            return gson.fromJson(responseBody, JsonObject.class);
        } else {
            throw new IllegalStateException("HTTP request returned error");
        }
    } catch (UnsupportedEncodingException e) {
        throw Exceptions.propagate(e);
    }
}
 
Example 4
Source File: SeaCloudsMonitoringInitializationPolicies.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
private void postSeaCloudsDcConfiguration(String requestBody) {

            URI apiEndpoint = URI.create(getConfig(SEACLOUDS_DC_ENDPOINT) + RESOURCES);

            Map<String, String> headers = MutableMap.of(
                    HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString(),
                    HttpHeaders.ACCEPT, MediaType.JSON_UTF_8.toString());

            HttpToolResponse response = HttpTool
                    .httpPost(HttpTool.httpClientBuilder().build(), apiEndpoint, headers, requestBody.getBytes());

            if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
                throw new RuntimeException("Something went wrong during SeaCloudsDc configuration, "
                        + response.getResponseCode() + ":" + response.getContentAsString());
            }
        }
 
Example 5
Source File: SeaCloudsManagementPolicy.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
private HttpToolResponse post(String url, String mediaType, String username, String password, byte[] payload) {
    URI apiEndpoint = URI.create(url);
    // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials

    if (username == null || password == null) {
        return HttpTool.httpPost(HttpTool.httpClientBuilder().build(), apiEndpoint,
                MutableMap.of(HttpHeaders.CONTENT_TYPE, mediaType, HttpHeaders.ACCEPT, mediaType), payload);
    } else {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

        // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials
        return HttpTool.httpPost(HttpTool.httpClientBuilder().uri(apiEndpoint).credentials(credentials).build(),
                apiEndpoint, MutableMap.of(HttpHeaders.CONTENT_TYPE, mediaType, HttpHeaders.ACCEPT, mediaType,
                        HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(credentials)), payload);
    }
}
 
Example 6
Source File: CouchbaseNodeImpl.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
protected void renameServerToPublicHostname() {
    // http://docs.couchbase.com/couchbase-manual-2.5/cb-install/#couchbase-getting-started-hostnames
    URI apiUri = null;
    try {
        HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getAttribute(COUCHBASE_WEB_ADMIN_PORT));
        apiUri = URI.create(String.format("http://%s:%d/node/controller/rename", accessible.getHostText(), accessible.getPort()));
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getConfig(COUCHBASE_ADMIN_USERNAME), getConfig(COUCHBASE_ADMIN_PASSWORD));
        HttpToolResponse response = HttpTool.httpPost(
                // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials
                HttpTool.httpClientBuilder().uri(apiUri).credentials(credentials).build(),
                apiUri,
                MutableMap.of(
                        HttpHeaders.CONTENT_TYPE, MediaType.FORM_DATA.toString(),
                        HttpHeaders.ACCEPT, "*/*",
                        // this appears needed; without it we get org.apache.http.NoHttpResponseException !?
                        HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(credentials)),
                Charsets.UTF_8.encode("hostname="+Urls.encode(accessible.getHostText())).array());
        log.debug("Renamed Couchbase server "+this+" via "+apiUri+": "+response);
        if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            log.warn("Invalid response code, renaming {} ({}): {}",
                    new Object[]{apiUri, response.getResponseCode(), response.getContentAsString()});
        }
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        log.warn("Error renaming server, using "+apiUri+": "+e, e);
    }
}
 
Example 7
Source File: HttpExecutorImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse execute(HttpRequest request) throws IOException {
    HttpConfig config = (request.config() != null) ? request.config() : DEFAULT_CONFIG;
    Credentials creds = (request.credentials() != null) ? new UsernamePasswordCredentials(request.credentials().getUser(), request.credentials().getPassword()) : null;
    HttpClient httpClient = HttpTool.httpClientBuilder()
            .uri(request.uri())
            .credential(Optional.fromNullable(creds))
            .laxRedirect(config.laxRedirect())
            .trustSelfSigned(config.trustSelfSigned())
            .trustAll(config.trustAll())
            .build();
    
    HttpToolResponse response;
    
    switch (request.method().toUpperCase()) {
    case HttpExecutor.GET:
        response = HttpTool.httpGet(httpClient, request.uri(), request.headers());
        break;
    case HttpExecutor.HEAD:
        response = HttpTool.httpHead(httpClient, request.uri(), request.headers());
        break;
    case HttpExecutor.POST:
        response = HttpTool.httpPost(httpClient, request.uri(), request.headers(), orEmpty(request.body()));
        break;
    case HttpExecutor.PUT:
        response = HttpTool.httpPut(httpClient, request.uri(), request.headers(), orEmpty(request.body()));
        break;
    case HttpExecutor.DELETE:
        response = HttpTool.httpDelete(httpClient, request.uri(), request.headers());
        break;
    default:
        throw new IllegalArgumentException("Unsupported method '"+request.method()+"' for URI "+request.uri());
    }
    return new HttpResponseWrapper(response);
}
 
Example 8
Source File: ScriptApiEntitlementsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpToolResponse httpPost(String user, String path, byte[] body) throws Exception {
    final ImmutableMap<String, String> headers = ImmutableMap.of(
            "Content-Type", "application/text");
    final URI uri = URI.create(getBaseUriRest()).resolve(path);
    return HttpTool.httpPost(newClient(user), uri, headers, body);
}
 
Example 9
Source File: CorsFilterLauncherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void test1CorsIsEnabledOnOneOriginPOST() throws IOException {
    final String shouldAllowOrigin = "http://foo.bar.com";
    final String thirdPartyOrigin = "http://foo.bar1.com";
    setCorsFilterFeature(true, ImmutableList.of(shouldAllowOrigin));
    HttpClient client = client();
    // preflight request
    HttpToolResponse response = HttpTool.execAndConsume(client, httpOptionsRequest("script/groovy", "POST", shouldAllowOrigin));
    assertAcAllowOrigin(response, shouldAllowOrigin, "POST");
    assertOkayResponse(response, "");
    
    response = HttpTool.httpPost(
            client, URI.create(getBaseUriRest() + "script/groovy"),
            ImmutableMap.<String,String>of(
                    "Origin", shouldAllowOrigin,
                    HttpHeaders.CONTENT_TYPE, "application/text"),
            "return 0;".getBytes());
    assertAcAllowOrigin(response, shouldAllowOrigin, "POST", false);
    assertOkayResponse(response, "{\"result\":\"0\"}");

    // preflight request
    response = HttpTool.execAndConsume(client, httpOptionsRequest("script/groovy", "POST", thirdPartyOrigin));
    assertAcNotAllowOrigin(response);
    assertOkayResponse(response, "");

    response = HttpTool.httpPost(
            client, URI.create(getBaseUriRest() + "script/groovy"),
            ImmutableMap.<String,String>of(
                    "Origin", thirdPartyOrigin,
                    HttpHeaders.CONTENT_TYPE, "application/text"),
            "return 0;".getBytes());
    assertAcNotAllowOrigin(response);
    assertOkayResponse(response, "{\"result\":\"0\"}");
}
 
Example 10
Source File: CorsFilterLauncherTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void test1CorsIsEnabledOnAllDomainsByDefaultPOST() throws IOException {
    final String shouldAllowOrigin = "http://foo.bar.com";
    BrooklynFeatureEnablement.enable(BrooklynFeatureEnablement.FEATURE_CORS_CXF_PROPERTY);
    BrooklynRestApiLauncher apiLauncher = baseLauncher().withoutJsgui();
    // In this test, management context has no value set for Allowed Origins.
    ManagementContext mgmt = LocalManagementContextForTests.builder(true)
            .useAdditionalProperties(MutableMap.<String, Object>of(
                    BrooklynFeatureEnablement.FEATURE_CORS_CXF_PROPERTY, true)
            ).build();
    apiLauncher.managementContext(mgmt);
    useServerForTest(apiLauncher.start());
    HttpClient client = client();
    // preflight request
    HttpToolResponse response = HttpTool.execAndConsume(client, httpOptionsRequest("script/groovy", "POST", shouldAllowOrigin));
    List<String> accessControlAllowOrigin = response.getHeaderLists().get(HEADER_AC_ALLOW_ORIGIN);
    assertEquals(accessControlAllowOrigin.size(), 1);
    assertEquals(accessControlAllowOrigin.get(0), "*", "Should allow POST requests made from " + shouldAllowOrigin);
    assertEquals(response.getHeaderLists().get(HEADER_AC_ALLOW_HEADERS).size(), 1);
    assertEquals(response.getHeaderLists().get(HEADER_AC_ALLOW_HEADERS).get(0), "x-csrf-token", "Should have asked and allowed x-csrf-token header from " + shouldAllowOrigin);
    assertOkayResponse(response, "");
    
    response = HttpTool.httpPost(
            client, URI.create(getBaseUriRest() + "script/groovy"),
            ImmutableMap.<String,String>of(
                    "Origin", shouldAllowOrigin,
                    HttpHeaders.CONTENT_TYPE, "application/text"),
            "return 0;".getBytes());
    accessControlAllowOrigin = response.getHeaderLists().get(HEADER_AC_ALLOW_ORIGIN);
    assertEquals(accessControlAllowOrigin.size(), 1);
    assertEquals(accessControlAllowOrigin.get(0), "*", "Should allow GET requests made from " + shouldAllowOrigin);
    assertOkayResponse(response, "{\"result\":\"0\"}");
}
 
Example 11
Source File: HttpToolIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups = {"Integration"})
public void testHttpPost() throws Exception {
    URI baseUri = new URI(httpService.getUrl());

    HttpClient client = HttpTool.httpClientBuilder().build();
    HttpToolResponse result = HttpTool.httpPost(client, baseUri, ImmutableMap.<String,String>of(), new byte[0]);
    assertTrue(new String(result.getContent()).contains("Hello, World"), "val="+new String(result.getContent()));
}
 
Example 12
Source File: HttpToolIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups = {"Integration"})
public void testHttpsPostWithTrustSelfSigned() throws Exception {
    URI baseUri = new URI(httpsService.getUrl());

    HttpClient client = HttpTool.httpClientBuilder().https(true).trustSelfSigned().build();
    HttpToolResponse result = HttpTool.httpPost(client, baseUri, ImmutableMap.<String,String>of(), new byte[0]);
    assertTrue(new String(result.getContent()).contains("Hello, World"), "val="+new String(result.getContent()));
}
 
Example 13
Source File: BrooklynNodeRestTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test(groups = "WIP")
public void testBrooklynNodeRestDeployAndMirror() {
    final SimpleYamlLauncher l = new SimpleYamlLauncherForTests();
    try {
        TestApplication app = TestApplication.Factory.newManagedInstanceForTests(l.getManagementContext());

        BrooklynNode bn = app.createAndManageChild(EntitySpec.create(BrooklynNode.class, SameBrooklynNodeImpl.class));
        bn.start(MutableSet.<Location>of());
        
        URI uri = bn.getAttribute(BrooklynNode.WEB_CONSOLE_URI);
        Assert.assertNotNull(uri);
        EntityAsserts.assertAttributeEqualsEventually(bn, Attributes.SERVICE_UP, true);
        log.info("Created BrooklynNode: "+bn);

        // deploy
        Task<?> t = bn.invoke(BrooklynNode.DEPLOY_BLUEPRINT, ConfigBag.newInstance()
            .configure(BrooklynNode.DeployBlueprintEffector.BLUEPRINT_TYPE, TestApplication.class.getName())
            .configure(BrooklynNode.DeployBlueprintEffector.BLUEPRINT_CONFIG, MutableMap.<String,Object>of("x", 1, "y", "Y"))
            .getAllConfig());
        log.info("Deployment result: "+t.getUnchecked());
        
        MutableSet<Application> apps = MutableSet.copyOf( l.getManagementContext().getApplications() );
        Assert.assertEquals(apps.size(), 2);
        apps.remove(app);
        
        Application newApp = Iterables.getOnlyElement(apps);
        Entities.dumpInfo(newApp);
        
        Assert.assertEquals(newApp.getConfig(new BasicConfigKey<Integer>(Integer.class, "x")), (Integer)1);
        
        // check mirror
        String newAppId = newApp.getId();
        BrooklynEntityMirror mirror = app.createAndManageChild(EntitySpec.create(BrooklynEntityMirror.class)
            .configure(BrooklynEntityMirror.MIRRORED_ENTITY_URL, 
                Urls.mergePaths(uri.toString(), "/v1/applications/"+newAppId+"/entities/"+newAppId))
            .configure(BrooklynEntityMirror.MIRRORED_ENTITY_ID, newAppId)
            .configure(BrooklynEntityMirror.POLL_PERIOD, Duration.millis(10)));
        
        Entities.dumpInfo(mirror);
        
        EntityAsserts.assertAttributeEqualsEventually(mirror, Attributes.SERVICE_UP, true);
        
        ((EntityInternal)newApp).sensors().set(TestEntity.NAME, "foo");
        EntityAsserts.assertAttributeEqualsEventually(mirror, TestEntity.NAME, "foo");
        log.info("Mirror successfully validated");
        
        // also try deploying by invoking deploy through json
        // (catch issues when effector params are map)
        HttpClient client = HttpTool.httpClientBuilder().build();
        HttpToolResponse result = HttpTool.httpPost(client, URI.create(Urls.mergePaths(uri.toString(), "/v1/applications/"+app.getId()+"/entities/"+bn.getId()
                +"/effectors/deployBlueprint")), 
            MutableMap.of(com.google.common.net.HttpHeaders.CONTENT_TYPE, "application/json"), 
            Jsonya.newInstance()
                .put("blueprintType", TestApplication.class.getName())
                .put("blueprintConfig", MutableMap.of(TestEntity.CONF_NAME.getName(), "foo"))
            .toString().getBytes());
        log.info("Deploy effector invoked, result: "+result);
        HttpTestUtils.assertHealthyStatusCode( result.getResponseCode() );
        
        Repeater.create().every(Duration.millis(10)).until(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return l.getManagementContext().getApplications().size() == 3;
            }
        }).limitTimeTo(Duration.TEN_SECONDS).runRequiringTrue();
        
        apps = MutableSet.copyOf( l.getManagementContext().getApplications() );
        apps.removeAll( MutableSet.of(app, newApp) );
        Application newApp2 = Iterables.getOnlyElement(apps);
        Entities.dumpInfo(newApp2);
        
        EntityAsserts.assertAttributeEqualsEventually(newApp2, Attributes.SERVICE_UP, true);
        Assert.assertEquals(newApp2.getConfig(TestEntity.CONF_NAME), "foo");
        
    } finally {
        l.destroyAll();
    }
    log.info("DONE");
}
 
Example 14
Source File: CsrfTokenFilterLauncherTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Test
public void testRequestToken() {
    useServerForTest(baseLauncher()
        .withoutJsgui()
        .start());

    HttpClient client = client();
    
    HttpToolResponse response = HttpTool.httpGet(
        client, URI.create(getBaseUriRest() + "server/ha/state"),
        ImmutableMap.<String,String>of(
            CsrfTokenFilter.CSRF_TOKEN_REQUIRED_HEADER, CsrfTokenFilter.CsrfTokenRequiredForRequests.WRITE.toString()));
    
    // comes back okay
    assertOkayResponse(response, "\"MASTER\"");
    
    Map<String, List<String>> cookies = response.getCookieKeyValues();
    String token = Iterables.getOnlyElement(cookies.get(CsrfTokenFilter.CSRF_TOKEN_VALUE_COOKIE));
    Assert.assertNotNull(token);
    String tokenAngular = Iterables.getOnlyElement(cookies.get(CsrfTokenFilter.CSRF_TOKEN_VALUE_COOKIE_ANGULAR_NAME));
    Assert.assertEquals(token, tokenAngular);
    
    // can post subsequently with token
    response = HttpTool.httpPost(
        client, URI.create(getBaseUriRest() + "script/groovy"),
        ImmutableMap.<String,String>of(
            HttpHeaders.CONTENT_TYPE, "application/text",
            CsrfTokenFilter.CSRF_TOKEN_VALUE_HEADER, token ),
        "return 0;".getBytes());
    assertOkayResponse(response, "{\"result\":\"0\"}");

    // but fails without token
    response = HttpTool.httpPost(
        client, URI.create(getBaseUriRest() + "script/groovy"),
        ImmutableMap.<String,String>of(
            HttpHeaders.CONTENT_TYPE, "application/text" ),
        "return 0;".getBytes());
    assertEquals(response.getResponseCode(), HttpStatus.SC_FORBIDDEN);

    // can get without token
    response = HttpTool.httpGet(
        client, URI.create(getBaseUriRest() + "server/ha/state"),
        ImmutableMap.<String,String>of());
    assertOkayResponse(response, "\"MASTER\"");
    
    // but if we set required ALL then need a token to get
    response = HttpTool.httpGet(
        client, URI.create(getBaseUriRest() + "server/ha/state"),
        ImmutableMap.<String,String>of(
            CsrfTokenFilter.CSRF_TOKEN_REQUIRED_HEADER, CsrfTokenFilter.CsrfTokenRequiredForRequests.ALL.toString().toLowerCase()
            ));
    assertOkayResponse(response, "\"MASTER\"");
    response = HttpTool.httpGet(
        client, URI.create(getBaseUriRest() + "server/ha/state"),
        ImmutableMap.<String,String>of());
    assertEquals(response.getResponseCode(), HttpStatus.SC_FORBIDDEN);
    
    // however note if we use a new client, with no session, then we can post with no token
    // (ie we don't guard against CSRF if your brooklyn is unsecured)
    client = client();
    response = HttpTool.httpPost(
        client, URI.create(getBaseUriRest() + "script/groovy"),
        ImmutableMap.<String,String>of(
            HttpHeaders.CONTENT_TYPE, "application/text" ),
        "return 0;".getBytes());
    assertOkayResponse(response, "{\"result\":\"0\"}");
}
 
Example 15
Source File: ServerResourceIntegrationTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/**
 * [sam] Other tests rely on brooklyn.properties not containing security properties so ..
 * I think the best way to test this is to set a security provider, then reload properties
 * and check no authentication is required.
 * 
 * [aled] Changing this test so doesn't rely on brooklyn.properties having no security
 * provider (that can lead to failures locally when running just this test). Asserts 
 */
@Test(groups = "Integration")
public void testSecurityProviderUpdatesWhenPropertiesReloaded() {
    BrooklynProperties brooklynProperties = BrooklynProperties.Factory.newEmpty();
    brooklynProperties.put("brooklyn.webconsole.security.users", "admin");
    brooklynProperties.put("brooklyn.webconsole.security.user.admin.password", "mypassword");
    UsernamePasswordCredentials defaultCredential = new UsernamePasswordCredentials("admin", "mypassword");

    ManagementContext mgmt = new LocalManagementContext(brooklynProperties);
    
    try {
        Server server = useServerForTest(baseLauncher()
                .managementContext(mgmt)
                .withoutJsgui()
                .securityProvider(TestSecurityProvider.class)
                .start());
        String baseUri = getBaseUriRest(server);

        HttpToolResponse response;
        final URI uri = URI.create(getBaseUriRest() + "server/properties/reload");
        final Map<String, String> args = Collections.emptyMap();

        // Unauthorised when no credentials, and when default credentials.
        response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).build(), uri, args, args);
        assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED);

        response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).credentials(defaultCredential).build(), 
                uri, args, args);
        assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED);

        // Accepts TestSecurityProvider credentials, and we reload.
        response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).credentials(TestSecurityProvider.CREDENTIAL).build(),
                uri, args, args);
        HttpAsserts.assertHealthyStatusCode(response.getResponseCode());

        // Has now gone back to credentials from brooklynProperties; TestSecurityProvider credentials no longer work
        response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).credentials(defaultCredential).build(), 
                uri, args, args);
        HttpAsserts.assertHealthyStatusCode(response.getResponseCode());
        
        response = HttpTool.httpPost(httpClientBuilder().uri(baseUri).credentials(TestSecurityProvider.CREDENTIAL).build(), 
                uri, args, args);
        assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED);

    } finally {
        ((ManagementContextInternal)mgmt).terminate();
    }
}
 
Example 16
Source File: BrooklynRestApiLauncherTestFixture.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected HttpToolResponse httpPost(String user, String path, byte[] body, Map<String, String> headers) throws Exception {
    final URI uri = URI.create(getBaseUriRest()).resolve(path);
    return HttpTool.httpPost(newClient(user), uri, headers, body);
}