Java源码示例:org.apache.brooklyn.util.http.HttpTool

示例1
@Override
public void init() {
    super.init();
    
    // defaulting to randomized subdomains makes deploying multiple applications easier
    if (config().get(RANDOMIZE_SUBDOMAIN_NAME) == null) {
        config().set(RANDOMIZE_SUBDOMAIN_NAME, true);
    }

    Boolean trustAll = config().get(SSL_TRUST_ALL);
    if (Boolean.TRUE.equals(trustAll)) {
        webClient = new GeoscalingWebClient(HttpTool.httpClientBuilder().trustAll().build());
    } else {
        webClient = new GeoscalingWebClient();
    }
}
 
示例2
@Test(groups = "Live", dataProvider="basicEntities")
public void testConcurrentDeploys(EntitySpec<? extends JavaWebAppSoftwareProcess> webServerSpec) throws Exception {
    JavaWebAppSoftwareProcess server = app.createAndManageChild(webServerSpec);
    app.start(ImmutableList.of(loc));
    EntityAsserts.assertAttributeEqualsEventually(server, Attributes.SERVICE_UP, Boolean.TRUE);
    Collection<Task<Void>> deploys = MutableList.of();
    for (int i = 0; i < 5; i++) {
        deploys.add(server.invoke(TomcatServer.DEPLOY, MutableMap.of("url", getTestWar(), "targetName", "/")));
    }
    for(Task<Void> t : deploys) {
        t.getUnchecked();
    }

    final HttpClient client = HttpTool.httpClientBuilder().build();
    final URI warUrl = URI.create(server.getAttribute(JavaWebAppSoftwareProcess.ROOT_URL));
    Asserts.succeedsEventually(new Runnable() {
        @Override
        public void run() {
            HttpToolResponse resp = HttpTool.httpGet(client, warUrl, ImmutableMap.<String,String>of());
            assertEquals(resp.getResponseCode(), 200);
        }
    });
}
 
示例3
@Override
@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
    // Want to load username and password from user's properties.
    mgmt = LocalManagementContextForTests.newInstance(BrooklynProperties.Factory.newDefault());

    String username = getBrooklynProperty(mgmt, "brooklyn.geoscaling.username");
    String password = getBrooklynProperty(mgmt, "brooklyn.geoscaling.password");
    if (username == null || password == null) {
        throw new SkipException("Set brooklyn.geoscaling.username and brooklyn.geoscaling.password in brooklyn.properties to enable test");
    }

    // Insecurely use "trustAll" so that don't need to import signature into trust store
    // before test will work on jenkins machine.
    HttpClient httpClient = HttpTool.httpClientBuilder().uri(GEOSCALING_URL).trustAll().build();
    geoscaling = new GeoscalingWebClient(httpClient);
    geoscaling.login(username, password);
    super.setUp();
}
 
示例4
/**
 * Confirm can read from URL.
 *
 * @param url
 */
public static boolean isUrlUp(URL url) {
    try {
        HttpToolResponse result = HttpTool.httpGet(
                HttpTool.httpClientBuilder().trustAll().build(), 
                URI.create(url.toString()), 
                ImmutableMap.<String,String>of());
        int statuscode = result.getResponseCode();

        if (statuscode != 200) {
            LOG.info("Error reading URL {}: {}, {}", new Object[]{url, statuscode, result.getReasonPhrase()});
            return false;
        } else {
            return true;
        }
    } catch (Exception e) {
        LOG.info("Error reading URL {}: {}", url, e);
        return false;
    }
}
 
示例5
private HttpToolResponse delete(String url, String mediaType, String username, String password) {
    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.httpDelete(HttpTool.httpClientBuilder().build(), apiEndpoint,
                MutableMap.of(HttpHeaders.CONTENT_TYPE, mediaType, HttpHeaders.ACCEPT, mediaType));
    } 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.httpDelete(HttpTool.httpClientBuilder().uri(apiEndpoint).credentials(credentials).build(),
                apiEndpoint,
                MutableMap.of(HttpHeaders.CONTENT_TYPE, mediaType, HttpHeaders.ACCEPT, mediaType,
                        HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(credentials)));
    }
}
 
示例6
@Test
public void verifySecurityInitializedExplicitUser() throws Exception {
    webServer = new BrooklynWebServer(newManagementContext(brooklynProperties));
    webServer.start();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("myuser", "somepass"));
    HttpClient client = HttpTool.httpClientBuilder()
        .credentials(new UsernamePasswordCredentials("myuser", "somepass"))
        .uri(webServer.getRootUrl())
        .build();

    try {
        HttpToolResponse response = HttpTool.execAndConsume(client, new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 401);
    } finally {
        webServer.stop();
    }
}
 
示例7
private void verifyHttpsFromConfig(BrooklynProperties brooklynProperties) throws Exception {
    webServer = new BrooklynWebServer(MutableMap.of(), newManagementContext(brooklynProperties));
    webServer.skipSecurity();
    webServer.start();
    
    try {
        KeyStore keyStore = load("client.ks", "password");
        KeyStore trustStore = load("client.ts", "password");
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "password", trustStore, (SecureRandom)null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpToolResponse response = HttpTool.execAndConsume(
                HttpTool.httpClientBuilder()
                        .port(webServer.getActualPort())
                        .https(true)
                        .socketFactory(socketFactory)
                        .build(),
                new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 200);
    } finally {
        webServer.stop();
    }
}
 
示例8
@Test(groups="Integration")
public void testStartsWebServerWithCredentials() throws Exception {
    launcher = newLauncherForTests(true)
            .restServerPort("10000+")
            .brooklynProperties(BrooklynWebConfig.USERS, "myname")
            .brooklynProperties(BrooklynWebConfig.PASSWORD_FOR_USER("myname"), "mypassword")
            .start();
    String uri = launcher.getServerDetails().getWebServerUrl();
    
    HttpToolResponse response = HttpTool.execAndConsume(HttpTool.httpClientBuilder().build(), new HttpGet(uri));
    assertEquals(response.getResponseCode(), 401);
    
    HttpToolResponse response2 = HttpTool.execAndConsume(
            HttpTool.httpClientBuilder()
                    .uri(uri)
                    .credentials(new UsernamePasswordCredentials("myname", "mypassword"))
                    .build(), 
            new HttpGet(uri));
    assertEquals(response2.getResponseCode(), 200);
}
 
示例9
@Test
public void testStartsAppViaEffector() throws Exception {
    URI webConsoleUri = URI.create(ENDPOINT_ADDRESS_HTTP); // BrooklynNode will append "/v1" to it

    EntitySpec<BrooklynNode> spec = EntitySpec.create(BrooklynNode.class);
    EntityManager mgr = getManagementContext().getEntityManager(); // getManagementContextFromJettyServerAttributes(server).getEntityManager();
    BrooklynNode node = mgr.createEntity(spec);
    node.sensors().set(BrooklynNode.WEB_CONSOLE_URI, webConsoleUri);
    mgr.manage(node);
    Map<String, String> params = ImmutableMap.of(DeployBlueprintEffector.BLUEPRINT_CAMP_PLAN.getName(), "{ services: [ serviceType: \"java:"+BasicApplication.class.getName()+"\" ] }");
    String id = node.invoke(BrooklynNode.DEPLOY_BLUEPRINT, params).getUnchecked();

    log.info("got: "+id);

    String apps = HttpTool.getContent(getEndpointAddress() + "/applications");
    List<String> appType = parseJsonList(apps, ImmutableList.of("spec", "type"), String.class);
    assertEquals(appType, ImmutableList.of(BasicApplication.class.getName()));

    String status = HttpTool.getContent(getEndpointAddress()+"/applications/"+id+"/entities/"+id+"/sensors/service.status");
    log.info("STATUS: "+status);
}
 
示例10
@Test
public void test1CorsIsEnabledOnAllDomainsGET() throws IOException {
    final String shouldAllowOrigin = "http://foo.bar.com";
    setCorsFilterFeature(true, ImmutableList.<String>of());
    HttpClient client = client();
    // preflight request
    HttpToolResponse response = HttpTool.execAndConsume(client, httpOptionsRequest("server/ha/state", "GET", shouldAllowOrigin));
    List<String> accessControlAllowOrigin = response.getHeaderLists().get(HEADER_AC_ALLOW_ORIGIN);
    assertEquals(accessControlAllowOrigin.size(), 1);
    assertEquals(accessControlAllowOrigin.get(0), "*", "Should allow GET 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, "");

    HttpUriRequest httpRequest = RequestBuilder.get(getBaseUriRest() + "server/ha/state")
            .addHeader("Origin", shouldAllowOrigin)
            .addHeader(HEADER_AC_REQUEST_METHOD, "GET")
            .build();
    response = HttpTool.execAndConsume(client, httpRequest);
    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, "\"MASTER\"");
}
 
示例11
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);
    }
}
 
示例12
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");
}
 
示例13
public VaultExternalConfigSupplier(ManagementContext managementContext, String name, Map<String, String> config) {
    super(managementContext, name);
    this.config = config;
    this.name = name;
    httpClient = HttpTool.httpClientBuilder().build();
    gson = new GsonBuilder().create();

    List<String> errors = Lists.newArrayListWithCapacity(2);
    endpoint = config.get("endpoint");
    if (Strings.isBlank(endpoint)) errors.add("missing configuration 'endpoint'");
    path = config.get("path");
    if (Strings.isBlank(path)) errors.add("missing configuration 'path'");
    if (!errors.isEmpty()) {
        String message = String.format("Problem configuration Vault external config supplier '%s': %s",
                name, Joiner.on(System.lineSeparator()).join(errors));
        throw new IllegalArgumentException(message);
    }

    token = initAndLogIn(config);
    headersWithToken = ImmutableMap.<String, String>builder()
            .putAll(MINIMAL_HEADERS)
            .put("X-Vault-Token", token)
            .build();
}
 
示例14
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);
    }
}
 
示例15
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());
            }
        }
 
示例16
private void installMonitoringRules() {
    LOG.info("SeaCloudsInitializerPolicy is installing T4C Monitoring Rules for " + entity.getId());

    HttpToolResponse response = post(getConfig(T4C_ENDPOINT) + "/v1/monitoring-rules", MediaType.APPLICATION_XML_UTF_8.toString(),
            getConfig(T4C_USERNAME), getConfig(T4C_PASSWORD), BaseEncoding.base64().decode(getConfig(T4C_RULES)));

    if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
        throw new RuntimeException("Something went wrong while the monitoring rules installation. " +
                "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString());
    } else {
        List<String> ruleIds = new ArrayList<>();

        for (MonitoringRule rule : monitoringRules.getMonitoringRules()) {
            ruleIds.add(rule.getId());
        }
        entity.sensors().set(T4C_IDS, ruleIds);
    }
}
 
示例17
private void installGrafanaDashboards() {
    try {
        HttpToolResponse response = post(getConfig(GRAFANA_ENDPOINT) + "/api/dashboards/db",
                MediaType.JSON_UTF_8.toString(), getConfig(GRAFANA_USERNAME),
                getConfig(GRAFANA_PASSWORD), grafanaInitializerPayload.getBytes());

        if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            throw new RuntimeException("Something went wrong while installing Grafana Dashboards. " +
                    "Invalid response code, " + response.getResponseCode() + ":" + response.getContentAsString());
        }

        // Retrieving unique slug to be able to remove the Dashboard later
        ObjectMapper mapper = new ObjectMapper();
        JsonNode json = mapper.readTree(response.getContent());
        grafanaDashboardSlug = json.get("slug").asText();
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        LOG.warn("Error installingGrafanaDashboards, using " + getConfig(GRAFANA_ENDPOINT) + "/api/dashboards/db {}", e);
    }
}
 
示例18
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);
    }
}
 
示例19
private HttpToolResponse getApiResponse(String uri) {
    return HttpTool.httpGet(HttpTool.httpClientBuilder()
                    // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials
                    .uri(uri)
                    .credentials(new UsernamePasswordCredentials(getUsername(), getPassword()))
                    .build(),
            URI.create(uri),
            ImmutableMap.<String, String>of());
}
 
示例20
@Test(groups = {"Integration"})
public void testHazelcastRestInterface() throws URISyntaxException {
    hazelcastNode = app.createAndManageChild(EntitySpec.create(HazelcastNode.class));
    app.start(ImmutableList.of(testLocation));

    EntityAsserts.assertAttributeEqualsEventually(hazelcastNode, Startable.SERVICE_UP, true);
    EntityAsserts.assertAttributeEquals(hazelcastNode, HazelcastNode.NODE_PORT, 5701);

    String baseUri = String.format("http://%s:%d/hazelcast/rest/cluster", hazelcastNode.getAttribute(Attributes.HOSTNAME), hazelcastNode.getAttribute(HazelcastNode.NODE_PORT)); 
    HttpToolResponse response = HttpTool.execAndConsume(
            HttpTool.httpClientBuilder().build(),
            new HttpGet(baseUri));
    assertEquals(response.getResponseCode(), 200);
}
 
示例21
@Test(groups = {"Integration"})
public void testDocumentCount() throws URISyntaxException {
    elasticSearchNode = app.createAndManageChild(EntitySpec.create(ElasticSearchNode.class));
    app.start(ImmutableList.of(testLocation));
    
    EntityAsserts.assertAttributeEqualsEventually(elasticSearchNode, Startable.SERVICE_UP, true);
    
    EntityAsserts.assertAttributeEquals(elasticSearchNode, ElasticSearchNode.DOCUMENT_COUNT, 0);
    
    String baseUri = "http://" + elasticSearchNode.getAttribute(Attributes.HOSTNAME) + ":" + elasticSearchNode.getAttribute(Attributes.HTTP_PORT);
    
    HttpToolResponse pingResponse = HttpTool.execAndConsume(
            HttpTool.httpClientBuilder().build(),
            new HttpGet(baseUri));
    assertEquals(pingResponse.getResponseCode(), 200);
    
    String document = "{\"foo\" : \"bar\",\"baz\" : \"quux\"}";
    
    HttpToolResponse putResponse = HttpTool.httpPut(
            HttpTool.httpClientBuilder()
                .port(elasticSearchNode.getAttribute(Attributes.HTTP_PORT))
                .build(), 
            new URI(baseUri + "/mydocuments/docs/1"), 
            ImmutableMap.<String, String>of(), 
            Strings.toByteArray(document)); 
    assertEquals(putResponse.getResponseCode(), 201);
    
    HttpToolResponse getResponse = HttpTool.execAndConsume(
            HttpTool.httpClientBuilder().build(),
            new HttpGet(baseUri + "/mydocuments/docs/1/_source"));
    assertEquals(getResponse.getResponseCode(), 200);
    assertEquals(HttpValueFunctions.jsonContents("foo", String.class).apply(getResponse), "bar");
    
    EntityAsserts.assertAttributeEqualsEventually(elasticSearchNode, ElasticSearchNode.DOCUMENT_COUNT, 1);
}
 
示例22
public static HttpToolResponse requestTokenWithExplicitLifetime(URL url, String user, String key, Duration expiration) throws URISyntaxException {
        HttpClient client = HttpTool.httpClientBuilder().build();
        HttpToolResponse response = HttpTool.httpGet(client, url.toURI(), MutableMap.<String,String>of()
            .add(AuthHeaders.AUTH_USER, user)
            .add(AuthHeaders.AUTH_KEY, key)
            .add("Host", url.getHost())
            .add("X-Auth-New-Token", "" + true)
            .add("X-Auth-Token-Lifetime", "" + expiration.toSeconds())
            );
//        curl -v https://ams01.objectstorage.softlayer.net/auth/v1.0/v1.0 -H "X-Auth-User: IBMOS12345-2:username" -H "X-Auth-Key: <API KEY>" -H "Host: ams01.objectstorage.softlayer.net" -H "X-Auth-New-Token: true" -H "X-Auth-Token-Lifetime: 15"
        log.info("Requested token with explicit lifetime: "+expiration+" at "+url+"\n"+response+"\n"+response.getHeaderLists());
        return response;
    }
 
示例23
@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);
}
 
示例24
private void initVars() {
    baseUrl = server.getUrl();
    httpClient = HttpTool.httpClientBuilder()
        .uri(baseUrl)
        .build();
    baseUri = URI.create(baseUrl);
    simpleEndpoint = testUri("/simple");
    executor = Executors.newScheduledThreadPool(3);
}
 
示例25
@Test
public void verifySecurityInitialized() throws Exception {
    webServer = new BrooklynWebServer(newManagementContext(brooklynProperties));
    webServer.start();
    try {
        HttpToolResponse response = HttpTool.execAndConsume(HttpTool.httpClientBuilder().build(), new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 401);
    } finally {
        webServer.stop();
    }
}
 
示例26
@Test(dataProvider="keystorePaths")
public void verifyHttps(String keystoreUrl) throws Exception {
    Map<String,?> flags = ImmutableMap.<String,Object>builder()
            .put("httpsEnabled", true)
            .put("keystoreUrl", keystoreUrl)
            .put("keystorePassword", "password")
            .build();
    webServer = new BrooklynWebServer(flags, newManagementContext(brooklynProperties));
    webServer.skipSecurity().start();
    
    try {
        KeyStore keyStore = load("client.ks", "password");
        KeyStore trustStore = load("client.ts", "password");
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "password", trustStore, (SecureRandom)null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpToolResponse response = HttpTool.execAndConsume(
                HttpTool.httpClientBuilder()
                        .port(webServer.getActualPort())
                        .https(true)
                        .socketFactory(socketFactory)
                        .build(),
                new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 200);
    } finally {
        webServer.stop();
    }
}
 
示例27
@Test(groups="Integration")
public void testStartsWebServerWithoutAuthentication() throws Exception {
    launcher = newLauncherForTests(true)
            .start();
    String uri = launcher.getServerDetails().getWebServerUrl();
    
    HttpToolResponse response = HttpTool.execAndConsume(HttpTool.httpClientBuilder().build(), new HttpGet(uri));
    assertEquals(response.getResponseCode(), 200);
}
 
示例28
@Override
public HttpTool.HttpClientBuilder getHttpClientForBrooklynNode() {
    String baseUrl = getEntityUrl();
    HttpTool.HttpClientBuilder builder = HttpTool.httpClientBuilder()
            .trustAll()
            .laxRedirect(true)
            .uri(baseUrl);
    if (entity.getConfig(BrooklynNode.MANAGEMENT_USER) != null) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                entity.getConfig(BrooklynNode.MANAGEMENT_USER),
                entity.getConfig(BrooklynNode.MANAGEMENT_PASSWORD));
        builder.credentials(credentials);
    }
    return builder;
}
 
示例29
@Override
public HttpToolResponse get(String path) {
    return exec(path, new HttpCall() {
        @Override
        public HttpToolResponse call(HttpClient client, URI uri) {
            return HttpTool.httpGet(client, uri, MutableMap.<String, String>of());
        }
    });
}
 
示例30
@Override
public HttpToolResponse post(String path, final Map<String, String> headers, final byte[] body) {
    return exec(path, new HttpCall() {
        @Override
        public HttpToolResponse call(HttpClient client, URI uri) {
            return HttpTool.httpPost(client, uri, headers, body);
        }
    });
}