Java Code Examples for org.apache.http.HttpHost#create()

The following examples show how to use org.apache.http.HttpHost#create() . 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: Elasticsearch6Configuration.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Parse Hosts String to list.
 *
 * <p>Hosts String format was given as following:
 *
 * <pre>
 *     connector.hosts = http://host_name:9092;http://host_name:9093
 * </pre>
 */
private static HttpHost validateAndParseHostsString(String host) {
	try {
		HttpHost httpHost = HttpHost.create(host);
		if (httpHost.getPort() < 0) {
			throw new ValidationException(String.format(
				"Could not parse host '%s' in option '%s'. It should follow the format 'http://host_name:port'. Missing port.",
				host,
				HOSTS_OPTION.key()));
		}

		if (httpHost.getSchemeName() == null) {
			throw new ValidationException(String.format(
				"Could not parse host '%s' in option '%s'. It should follow the format 'http://host_name:port'. Missing scheme.",
				host,
				HOSTS_OPTION.key()));
		}
		return httpHost;
	} catch (Exception e) {
		throw new ValidationException(String.format(
			"Could not parse host '%s' in option '%s'. It should follow the format 'http://host_name:port'.",
			host,
			HOSTS_OPTION.key()), e);
	}
}
 
Example 2
Source File: Elasticsearch7Configuration.java    From flink with Apache License 2.0 6 votes vote down vote up
private static HttpHost validateAndParseHostsString(String host) {
	try {
		HttpHost httpHost = HttpHost.create(host);
		if (httpHost.getPort() < 0) {
			throw new ValidationException(String.format(
				"Could not parse host '%s' in option '%s'. It should follow the format 'http://host_name:port'. Missing port.",
				host,
				HOSTS_OPTION.key()));
		}

		if (httpHost.getSchemeName() == null) {
			throw new ValidationException(String.format(
				"Could not parse host '%s' in option '%s'. It should follow the format 'http://host_name:port'. Missing scheme.",
				host,
				HOSTS_OPTION.key()));
		}
		return httpHost;
	} catch (Exception e) {
		throw new ValidationException(String.format(
			"Could not parse host '%s' in option '%s'. It should follow the format 'http://host_name:port'.",
			host,
			HOSTS_OPTION.key()), e);
	}
}
 
Example 3
Source File: JavaBrokerAdmin.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public JavaBrokerAdmin() throws NamingException
{
    final Hashtable<String, String> env = new Hashtable<>();
    _context = new InitialContext(env);

    final String managementUser = System.getProperty("joramtests.manangement-user", "guest");
    final String managementPassword = System.getProperty("joramtests.manangement-password", "guest");

    _virtualhostnode = System.getProperty("joramtests.broker-virtualhostnode", "default");
    _virtualhost = System.getProperty("joramtests.broker-virtualhost", "default");

    _management = HttpHost.create(System.getProperty("joramtests.manangement-url", "http://localhost:8080"));
    _queueApiUrl = System.getProperty("joramtests.manangement-api-queue", "/api/latest/queue/%s/%s/%s");
    _topicApiUrl = System.getProperty("joramtests.manangement-api-topic", "/api/latest/exchange/%s/%s/%s");

    _credentialsProvider = getCredentialsProvider(managementUser, managementPassword);
    _httpClientContext = getHttpClientContext(_management);
}
 
Example 4
Source File: ManageQpidJMSResources.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public ManageQpidJMSResources()
{
    _objectMapper = new ObjectMapper();
    _objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);

    final String managementUser = System.getProperty("tck.management-username");
    final String managementPassword = System.getProperty("tck.management-password");

    _virtualhostnode = System.getProperty("tck.broker-virtualhostnode", "default");
    _virtualhost = System.getProperty("tck.broker-virtualhost", "default");

    _management = HttpHost.create(System.getProperty("tck.management-url", "http://localhost:8080"));
    _queueApiUrl = System.getProperty("tck.management-api-queue", "/api/latest/queue/%s/%s/%s");
    _queueApiClearQueueUrl = System.getProperty("tck.management-api-queue-clear", "/api/latest/queue/%s/%s/%s/clearQueue");
    _topicApiUrl = System.getProperty("tck.management-api-topic", "/api/latest/exchange/%s/%s/%s");

    _credentialsProvider = getCredentialsProvider(managementUser, managementPassword);
    _httpClientContext = getHttpClientContext(_management);
}
 
Example 5
Source File: ElasticRestClient.java    From elastic-rabbitmq with MIT License 6 votes vote down vote up
@Override
    public RestClient createInstance() throws Exception {
        if (this.restClient != null) {
            return this.restClient;
        }

        HttpHost[] addresses = new HttpHost[hosts.size()];
        for (int i = 0; i < hosts.size(); i++) {
            addresses[i] = HttpHost.create(hosts.get(i));
        }

        this.restClient = RestClient
                .builder(addresses)
                .setMaxRetryTimeoutMillis(ESConstants.RESTCLIENT_TIMEOUT)
                .build();

//        this.sniffer = Sniffer.builder(this.restClient)
//                                 .setSniffIntervalMillis(60000).build();

        return this.restClient;
    }
 
Example 6
Source File: ApacheHttpClientTagAdapterTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
GetRequestUrlScenario(
    boolean requestIsNull, boolean requestIsWrapper, Object baseUri, boolean targetIsNull,
    String targetUri, String expectedResult
) {
    this.expectedResult = expectedResult;
    HttpRequest request = null;

    if (!requestIsNull) {
        request = (requestIsWrapper) ? mock(HttpRequestWrapper.class) : mock(HttpRequest.class);
        RequestLine requestLine = mock(RequestLine.class);
        doReturn(requestLine).when(request).getRequestLine();
        doReturn(baseUri).when(requestLine).getUri();

        if (!targetIsNull) {
            HttpHost target = HttpHost.create(targetUri);
            doReturn(target).when((HttpRequestWrapper) request).getTarget();
        }
    }

    this.requestMock = request;
}
 
Example 7
Source File: NomadApiConfiguration.java    From nomad-java-sdk with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Validates a Nomad address and converts it to an HttpHost.
 *
 * @param address HTTP address of the agent to connect to, as an HTTP or HTTPS URL
 */
public static HttpHost nomadAddressAsHttpHost(String address) {
    if (!address.startsWith("http:") && !address.startsWith("https:")) {
        throw new IllegalArgumentException(
                "address must start with \"http:\" or \"https:\", but got \"" + address + "\"");
    }
    return HttpHost.create(address);
}
 
Example 8
Source File: ElasticRestClientImpl.java    From jframe with Apache License 2.0 5 votes vote down vote up
@Start
void start() {
    String[] hosts = Plugin.getConfig(HTTP_HOST, "localhost:9200").split(" ");
    HttpHost[] httpHosts = new HttpHost[hosts.length];
    for (int i = 0; i < hosts.length; ++i) {
        httpHosts[i] = HttpHost.create(hosts[i]);
    }
    client = RestClient.builder(httpHosts).setRequestConfigCallback(new CustomRequesetConfig()).build();
    LOG.info("{} start succ", ElasticRestClientImpl.class.getName());
}
 
Example 9
Source File: ElasticsearchPlugin.java    From hawkular-alerts with Apache License 2.0 5 votes vote down vote up
protected void writeAlert(Action a) throws Exception {
    String url = a.getProperties().get(PROP_URL);
    String index = a.getProperties().get(PROP_INDEX);
    String type = a.getProperties().get(PROP_TYPE);
    String[] urls = url.split(",");
    HttpHost[] hosts = new HttpHost[urls.length];
    for (int i=0; i<urls.length; i++) {
        hosts[i] = HttpHost.create(urls[0]);
    }
    RestClient client = RestClient.builder(hosts)
            .setHttpClientConfigCallback(httpClientBuilder -> {
                httpClientBuilder.useSystemProperties();
                CredentialsProvider credentialsProvider = checkBasicCredentials(a);
                if (credentialsProvider != null) {
                    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                }
                return httpClientBuilder;
            }).build();

    HttpEntity document = new NStringEntity(transform(a), ContentType.APPLICATION_JSON);
    String endpoint = "/" + index + "/" + type;
    Header[] headers = checkHeaders(a);
    Response response = headers == null ? client.performRequest("POST", endpoint, Collections.EMPTY_MAP, document) :
            client.performRequest("POST", endpoint, Collections.EMPTY_MAP, document, headers);
    log.debugf(response.toString());
    client.close();
}
 
Example 10
Source File: TestElasticsearchHTTP.java    From hangout with MIT License 5 votes vote down vote up
@Test
public void TestElasticsearchHTTP() {
    HttpHost host = null;

    host = HttpHost.create("");
    Assert.assertEquals(host.getSchemeName(), "http");
    Assert.assertEquals(host.getAddress(), null);
    Assert.assertEquals(host.getHostName(), "");
    Assert.assertEquals(host.getPort(), -1);

    host = HttpHost.create("192.168.0.100");
    Assert.assertEquals(host.getSchemeName(), "http");
    Assert.assertEquals(host.getAddress(), null);
    Assert.assertEquals(host.getHostName(), "192.168.0.100");
    Assert.assertEquals(host.getPort(), -1);

    host = HttpHost.create("192.168.0.100:80");
    Assert.assertEquals(host.getSchemeName(), "http");
    Assert.assertEquals(host.getAddress(), null);
    Assert.assertEquals(host.getHostName(), "192.168.0.100");
    Assert.assertEquals(host.getPort(), 80);

    host = HttpHost.create("http://192.168.0.100");
    Assert.assertEquals(host.getSchemeName(), "http");
    Assert.assertEquals(host.getAddress(), null);
    Assert.assertEquals(host.getHostName(), "192.168.0.100");
    Assert.assertEquals(host.getPort(), -1);

    host = HttpHost.create("https://192.168.0.100");
    Assert.assertEquals(host.getSchemeName(), "https");
    Assert.assertEquals(host.getAddress(), null);
    Assert.assertEquals(host.getHostName(), "192.168.0.100");
    Assert.assertEquals(host.getPort(), -1);
}
 
Example 11
Source File: BlockingHttpClientTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  when(filterable.call()).thenReturn(httpResponse);
  when(httpResponse.getStatusLine()).thenReturn(statusLine);
  when(statusLine.getStatusCode()).thenReturn(SC_OK);
  
  when(autoBlockConfiguration.shouldBlock(SC_UNAUTHORIZED)).thenReturn(true);
  when(autoBlockConfiguration.shouldBlock(SC_BAD_GATEWAY)).thenReturn(true);
  when(autoBlockConfiguration.shouldBlock(SC_PROXY_AUTHENTICATION_REQUIRED)).thenReturn(true);
  
  httpHost = HttpHost.create("localhost");
  underTest = new BlockingHttpClient(httpClient, new Config(), statusObserver, true, autoBlockConfiguration);
}
 
Example 12
Source File: HttpClientTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testGetHttpHost()
{
    HttpHost httpHost = HttpHost.create(VIVIDUS_ORG);
    httpClient.setHttpHost(httpHost);
    assertEquals(httpHost, httpClient.getHttpHost());
}
 
Example 13
Source File: QpidRestAPIQueueCreator.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public QpidRestAPIQueueCreator()
{
    final String managementUser = System.getProperty("perftests.manangement-user", "guest");
    final String managementPassword = System.getProperty("perftests.manangement-password", "guest");

    _virtualhostnode = System.getProperty("perftests.broker-virtualhostnode", "default");
    _virtualhost = System.getProperty("perftests.broker-virtualhost", "default");

    _management = HttpHost.create(System.getProperty("perftests.manangement-url", "http://localhost:8080"));
    _queueApiUrl = System.getProperty("perftests.manangement-api-queue", "/api/latest/queue/%s/%s/%s");
    _brokerApiUrl = System.getProperty("perftests.manangement-api-broker", "/api/latest/broker");

    _credentialsProvider = getCredentialsProvider(managementUser, managementPassword);
}
 
Example 14
Source File: EsRestClient.java    From jkes with Apache License 2.0 5 votes vote down vote up
@Inject
public EsRestClient(JkesProperties jkesProperties) {
    SniffOnFailureListener sniffOnFailureListener = new SniffOnFailureListener();
    Header[] defaultHeaders = {new BasicHeader("Content-Type", "application/json")};

    String[] urls = jkesProperties.getEsBootstrapServers().split("\\s*,");
    HttpHost[] hosts = new HttpHost[urls.length];
    for (int i = 0; i < urls.length; i++) {
        hosts[i] = HttpHost.create(urls[i]);
    }

    RestClient restClient = RestClient.builder(hosts)
            .setRequestConfigCallback(requestConfigBuilder -> {
                return requestConfigBuilder.setConnectTimeout(5000) // default 1s
                        .setSocketTimeout(60000); // defaults to 30 seconds
            }).setHttpClientConfigCallback(httpClientBuilder -> {
                return httpClientBuilder.setDefaultIOReactorConfig(
                        IOReactorConfig.custom().setIoThreadCount(2).build()); // because only used for admin, so not necessary to hold many worker threads
            })
            .setMaxRetryTimeoutMillis(60000) // defaults to 30 seconds
            .setDefaultHeaders(defaultHeaders)
            .setFailureListener(sniffOnFailureListener)
            .build();

    Sniffer sniffer = Sniffer.builder(restClient).build();
    sniffOnFailureListener.setSniffer(sniffer);

    this.sniffer = sniffer;
    this.restClient = restClient;
}
 
Example 15
Source File: EsRestClient.java    From jkes with Apache License 2.0 5 votes vote down vote up
@Autowired
public EsRestClient(JkesSearchProperties jkesProperties) {
    SniffOnFailureListener sniffOnFailureListener = new SniffOnFailureListener();
    Header[] defaultHeaders = {new BasicHeader("Content-Type", "application/json")};

    String[] urls = jkesProperties.getEs().getServers().split("\\s*,");
    HttpHost[] hosts = new HttpHost[urls.length];
    for (int i = 0; i < urls.length; i++) {
        hosts[i] = HttpHost.create(urls[i]);
    }

    RestClient restClient = RestClient.builder(hosts)
            .setRequestConfigCallback(requestConfigBuilder -> {
                return requestConfigBuilder.setConnectTimeout(5000) // default 1s
                        .setSocketTimeout(60000); // defaults to 30 seconds
            }).setHttpClientConfigCallback(httpClientBuilder -> {
                return httpClientBuilder.setDefaultIOReactorConfig(
                        IOReactorConfig.custom().setIoThreadCount(2).build()); // because only used for admin, so not necessary to hold many worker threads
            })
            .setMaxRetryTimeoutMillis(60000) // defaults to 30 seconds
            .setDefaultHeaders(defaultHeaders)
            .setFailureListener(sniffOnFailureListener)
            .build();

    Sniffer sniffer = Sniffer.builder(restClient).build();
    sniffOnFailureListener.setSniffer(sniffer);

    this.sniffer = sniffer;
    this.restClient = restClient;
}
 
Example 16
Source File: HttpClientTests.java    From vividus with Apache License 2.0 5 votes vote down vote up
@Test
void testDoHttpGet() throws Exception
{
    HttpHost httpHost = HttpHost.create(VIVIDUS_ORG);
    httpClient.setHttpHost(httpHost);
    CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
    HttpContext context = null;
    HttpEntity httpEntity = mock(HttpEntity.class);
    byte[] body = { 0, 1, 2 };
    Header[] headers = { header };
    StatusLine statusLine = mock(StatusLine.class);
    int statusCode = HttpStatus.SC_OK;
    when(httpEntity.getContent()).thenReturn(new ByteArrayInputStream(body));
    when(closeableHttpResponse.getEntity()).thenReturn(httpEntity);
    when(closeableHttpResponse.getAllHeaders()).thenReturn(headers);
    when(statusLine.getStatusCode()).thenReturn(statusCode);
    when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine);
    when(closeableHttpClient.execute(eq(httpHost), isA(HttpGet.class), eq(context)))
            .thenAnswer(getAnswerWithSleep(closeableHttpResponse));
    HttpResponse httpResponse = httpClient.doHttpGet(URI_TO_GO);
    assertEquals(VIVIDUS_ORG, httpResponse.getFrom().toString());
    assertEquals(GET, httpResponse.getMethod());
    assertArrayEquals(body, httpResponse.getResponseBody());
    assertArrayEquals(headers, httpResponse.getResponseHeaders());
    assertEquals(statusCode, httpResponse.getStatusCode());
    assertThat(httpResponse.getResponseTimeInMs(), greaterThan(0L));
}
 
Example 17
Source File: TestRestClient.java    From jframe with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void init() {
    HttpHost host = HttpHost.create("127.0.0.1:9200");
    client = RestClient.builder(host).build();
}
 
Example 18
Source File: MailWebApi.java    From sendcloud4j with MIT License 4 votes vote down vote up
public MailWebApi viaProxy(String proxy) {
    this.proxy = HttpHost.create(proxy);
    return this;
}
 
Example 19
Source File: RestClientTest.java    From hugegraph-common with Apache License 2.0 4 votes vote down vote up
@Test
public void testCleanExecutor() throws Exception {
    // Modify IDLE_TIME 100ms to speed test
    int newIdleTime = 100;
    int newCheckPeriod = newIdleTime + 20;

    RestClient client = new RestClientImpl("/test", 1000, newIdleTime,
                                           10, 5, 200);

    PoolingHttpClientConnectionManager pool;
    pool = Whitebox.getInternalState(client, "pool");
    pool = Mockito.spy(pool);
    Whitebox.setInternalState(client, "pool", pool);
    HttpRoute route = new HttpRoute(HttpHost.create(
                                    "http://127.0.0.1:8080"));
    // Create a connection manually, it will be put into leased list
    HttpClientConnection conn = pool.requestConnection(route, null)
                                    .get(1L, TimeUnit.SECONDS);
    PoolStats stats = pool.getTotalStats();
    int usingConns = stats.getLeased() + stats.getPending();
    Assert.assertGte(1, usingConns);

    // Sleep more than two check periods for busy connection
    Thread.sleep(newCheckPeriod);
    Mockito.verify(pool, Mockito.never()).closeExpiredConnections();
    stats = pool.getTotalStats();
    usingConns = stats.getLeased() + stats.getPending();
    Assert.assertGte(1, usingConns);

    // The connection will be put into available list
    pool.releaseConnection(conn, null, 0, TimeUnit.SECONDS);

    stats = pool.getTotalStats();
    usingConns = stats.getLeased() + stats.getPending();
    Assert.assertEquals(0, usingConns);
    /*
     * Sleep more than two check periods for free connection,
     * ensure connection has been closed
     */
    Thread.sleep(newCheckPeriod);
    Mockito.verify(pool, Mockito.atLeastOnce())
           .closeExpiredConnections();
    Mockito.verify(pool, Mockito.atLeastOnce())
           .closeIdleConnections(newIdleTime, TimeUnit.MILLISECONDS);
}
 
Example 20
Source File: HttpClientFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 4 votes vote down vote up
public void setProxy(String proxyString) {
    proxy = StringUtils.isBlank(proxyString) ? null : HttpHost.create(proxyString);
    getRequestConfigBuilder().setProxy(proxy);
}