Java Code Examples for org.elasticsearch.client.transport.TransportClient

The following examples show how to use org.elasticsearch.client.transport.TransportClient. These examples are extracted from open source projects. 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 Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: CustomFieldMaskedComplexMappingTest.java    License: Apache License 2.0 7 votes vote down vote up
@Override
protected void populateData(TransportClient tc) {

    try {
        tc.admin().indices().create(new CreateIndexRequest("logs").mapping("_doc", FileHelper.loadFile("dlsfls/masked_field_mapping.json"), XContentType.JSON)).actionGet();


        byte[] data = FileHelper.loadFile("dlsfls/logs_bulk_data.json").getBytes(StandardCharsets.UTF_8);
        BulkRequest br = new BulkRequest().add(data, 0, data.length, XContentType.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE);
        if(tc.bulk(br).actionGet().hasFailures()) {
            Assert.fail("bulk import failed");
        }
        Thread.sleep(1000);

    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.toString());
    }

}
 
Example #2
Source Project: Transwarp-Sample-Code   Author: TranswarpCN   File: SearchES.java    License: MIT License 6 votes vote down vote up
/**
 * 多字段查询
 */
public static void multisearch() {
    try {
        Settings settings = Settings.settingsBuilder().put("cluster.name", "elasticsearch1").build();
        TransportClient transportClient = TransportClient.builder().
                settings(settings).build().addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("172.16.2.93"), 9300));
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch("service2","clients");
        SearchResponse searchResponse = searchRequestBuilder.
                setQuery(QueryBuilders.boolQuery()
                        .should(QueryBuilders.termQuery("id","5"))
                        .should(QueryBuilders.prefixQuery("content","oracle")))
                .setFrom(0).setSize(100).setExplain(true).execute().actionGet();
        SearchHits searchHits = searchResponse.getHits();
        System.out.println();
        System.out.println("Total Hits is " + searchHits.totalHits());
        System.out.println();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #3
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: BulkProcessorObjectFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void failureHandlerExecutesFailoverForEachBatchItemSeparately() {

    // given
    Builder builder = createTestObjectFactoryBuilder();
    ClientObjectFactory<TransportClient, BulkRequest> config = builder.build();

    FailoverPolicy failoverPolicy = spy(new NoopFailoverPolicy());

    String payload1 = "test1";
    String payload2 = "test2";
    BulkRequest bulk = new BulkRequest()
            .add(spy(new IndexRequest().source(payload1, XContentType.CBOR)))
            .add(spy(new IndexRequest().source(payload2, XContentType.CBOR)));

    // when
    config.createFailureHandler(failoverPolicy).apply(bulk);

    // then
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(failoverPolicy, times(2)).deliver(captor.capture());

    assertTrue(captor.getAllValues().contains(payload1));
    assertTrue(captor.getAllValues().contains(payload2));
}
 
Example #4
Source Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: DlsDateMathTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void populateData(TransportClient tc) {



    LocalDateTime yesterday = LocalDateTime.now(ZoneId.of("UTC")).minusDays(1);
    LocalDateTime today = LocalDateTime.now(ZoneId.of("UTC"));
    LocalDateTime tomorrow = LocalDateTime.now(ZoneId.of("UTC")).plusDays(1);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
    
    tc.index(new IndexRequest("logstash").type("_doc").id("1").setRefreshPolicy(RefreshPolicy.IMMEDIATE)
            .source("{\"@timestamp\": \""+formatter.format(yesterday)+"\"}", XContentType.JSON)).actionGet();
    tc.index(new IndexRequest("logstash").type("_doc").id("2").setRefreshPolicy(RefreshPolicy.IMMEDIATE)
            .source("{\"@timestamp\": \""+formatter.format(today)+"\"}", XContentType.JSON)).actionGet();
    tc.index(new IndexRequest("logstash").type("_doc").id("3").setRefreshPolicy(RefreshPolicy.IMMEDIATE)
            .source("{\"@timestamp\": \""+formatter.format(tomorrow)+"\"}", XContentType.JSON)).actionGet();
}
 
Example #5
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: BulkProcessorObjectFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void configReturnsACopyOfServerUrisList() {

    // given
    Builder builder = createTestObjectFactoryBuilder();
    builder.withServerUris("http://localhost:9200;http://localhost:9201;http://localhost:9202");
    ClientObjectFactory<TransportClient, BulkRequest> config = builder.build();

    // when
    Collection<String> serverUrisList = config.getServerList();
    serverUrisList.add("test");

    // then
    assertNotEquals(serverUrisList.size(), config.getServerList().size());

}
 
Example #6
Source Project: presto-connectors   Author: harbby   File: Elasticsearch6Module.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Client get()
{
    try {
        Settings settings = Settings.builder().put("cluster.name", clusterName)
                .put("client.transport.sniff", true).build();

        TransportClient client = new PreBuiltTransportClient(settings);
        for (String ip : hosts.split(",")) {
            client.addTransportAddress(
                    new TransportAddress(InetAddress.getByName(ip.split(":")[0]),
                            Integer.parseInt(ip.split(":")[1])));
        }
        return client;
    }
    catch (IOException e) {
        throw new PrestoException(UNEXPECTED_ES_ERROR, "Failed to get connection to Elasticsearch", e);
    }
}
 
Example #7
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: BulkProcessorObjectFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void failureHandlerExecutesFailoverForEachBatchItemSeparately() {

    // given
    Builder builder = createTestObjectFactoryBuilder();
    ClientObjectFactory<TransportClient, BulkRequest> config = builder.build();

    FailoverPolicy failoverPolicy = spy(new NoopFailoverPolicy());

    String payload1 = "test1";
    String payload2 = "test2";
    BulkRequest bulk = new BulkRequest()
            .add(spy(new IndexRequest().source(payload1)))
            .add(spy(new IndexRequest().source(payload2)));

    // when
    config.createFailureHandler(failoverPolicy).apply(bulk);

    // then
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(failoverPolicy, times(2)).deliver((String) captor.capture());

    assertTrue(captor.getAllValues().contains(payload1));
    assertTrue(captor.getAllValues().contains(payload2));
}
 
Example #8
Source Project: logstash   Author: mesos   File: ElasticsearchContainer.java    License: Apache License 2.0 6 votes vote down vote up
public Client createClient() {
    final AtomicReference<Client> elasticsearchClient = new AtomicReference<>();
    await().atMost(30, TimeUnit.SECONDS).pollDelay(1, TimeUnit.SECONDS).until(() -> {
        Client c = new TransportClient(ImmutableSettings.settingsBuilder().put("cluster.name", elasticsearchClusterName).build()).addTransportAddress(new InetSocketTransportAddress(getIpAddress(), 9300));
        try {
            c.admin().cluster().health(Requests.clusterHealthRequest("_all")).actionGet();
        } catch (ElasticsearchException e) {
            c.close();
            return false;
        }
        elasticsearchClient.set(c);
        return true;
    });
    assertEquals(elasticsearchClusterName, elasticsearchClient.get().admin().cluster().health(Requests.clusterHealthRequest("_all")).actionGet().getClusterName());
    return elasticsearchClient.get();
}
 
Example #9
Source Project: AsuraFramework   Author: AsuraTeam   File: EshClientFactory.java    License: Apache License 2.0 6 votes vote down vote up
public TransportClient getClient()   {
    if (esClient == null) {
        synchronized (this) {
            if (esClient == null) {
                try {
                    //判断配置
                    Preconditions.checkNotNull(clusterName, "es 服务clusterName未配置");
                    Preconditions.checkNotNull(addresses, "es 服务ip未配置");
                    //Preconditions.checkArgument(esPort > 0, "es 服务服务port未配置");
                    //设置集群的名字
                    Settings settings = Settings.settingsBuilder().put("client.node", true).put("cluster.name", clusterName).put("client.transport.sniff", sniff).build();
                    //Settings settings = Settings.settingsBuilder().put("client.transport.sniff", sniff).build();
                    //创建集群client并添加集群节点地址
                    esClient = TransportClient.builder().settings(settings).build();
                    for (String address : addresses) {
                        String[] inetAddress = address.split(":");
                        esClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(inetAddress[0]), new Integer(inetAddress[1])));
                    }
                  }catch (Exception e){
                     LOGGER.error("客户端连接初始化异常",e);
                }
            }
        }
    }
    return esClient;
}
 
Example #10
Source Project: syncer   Author: zzt93   File: ElasticsearchConnection.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * @see org.elasticsearch.transport.TcpTransport#TCP_CONNECT_TIMEOUT
 */
public AbstractClient esClient() throws Exception {
  // https://discuss.elastic.co/t/getting-availableprocessors-is-already-set-to-1-rejecting-1-illegalstateexception-exception/103082
  System.setProperty("es.set.netty.runtime.available.processors", "false");

  TransportClient client = new PreBuiltXPackTransportClient(settings());
  for (String clusterNode : getClusterNodes()) {
    String hostName = substringBeforeLast(clusterNode, COLON);
    String port = substringAfterLast(clusterNode, COLON);
    Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'");
    Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'");
    logger.info("Adding transport node : {}, timeout in 30s", clusterNode);
    client.addTransportAddress(
        new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port)));
  }
  return client;
}
 
Example #11
Source Project: Elasticsearch-Tutorial-zh-CN   Author: judasn   File: BaseDemo.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 批量删除
 *
 * @param transportClient
 */
private static void batchDelete(TransportClient transportClient) throws IOException {
	BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();

	DeleteRequestBuilder deleteRequestBuilder1 = transportClient.prepareDelete("product_index", "product", "1");
	DeleteRequestBuilder deleteRequestBuilder2 = transportClient.prepareDelete("product_index", "product", "2");
	DeleteRequestBuilder deleteRequestBuilder3 = transportClient.prepareDelete("product_index", "product", "3");

	bulkRequestBuilder.add(deleteRequestBuilder1);
	bulkRequestBuilder.add(deleteRequestBuilder2);
	bulkRequestBuilder.add(deleteRequestBuilder3);

	BulkResponse bulkResponse = bulkRequestBuilder.get();
	for (BulkItemResponse bulkItemResponse : bulkResponse.getItems()) {
		logger.info("--------------------------------version= " + bulkItemResponse.getVersion());
	}

}
 
Example #12
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: BulkProcessorObjectFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void clientIsInitializedOnlyOnce() {

    // given
    BulkProcessorObjectFactory factory = spy(createTestObjectFactoryBuilder().build());

    BulkProcessorObjectFactory.InsecureTransportClientProvider clientProvider =
            new BulkProcessorObjectFactory.InsecureTransportClientProvider();

    when(factory.getClientProvider()).thenReturn(spy(clientProvider));

    // when
    TransportClient client1 = factory.createClient();
    TransportClient client2 = factory.createClient();

    // then
    verify(factory, times(1)).getClientProvider();
    assertEquals(client1, client2);

}
 
Example #13
Source Project: cloud-service   Author: allenyiwen   File: ElasticSearchConfig.java    License: MIT License 6 votes vote down vote up
/**
    * 使用elasticsearch实现类时才触发
    *
    * @return
    */
@Bean
   @ConditionalOnBean(value = EsLogServiceImpl.class)
public TransportClient getESClient() {
	// 设置集群名字
	Settings settings = Settings.builder().put("cluster.name", this.clusterName).build();
	TransportClient client = new PreBuiltTransportClient(settings);
	try {
		// 读取的ip列表是以逗号分隔的
		for (String clusterNode : this.clusterNodes.split(",")) {
			String ip = clusterNode.split(":")[0];
			String port = clusterNode.split(":")[1];
			((TransportClient) client)
					.addTransportAddress(new TransportAddress(InetAddress.getByName(ip), Integer.parseInt(port)));
		}
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}

	return client;
}
 
Example #14
Source Project: skywalking   Author: apache   File: CaseController.java    License: Apache License 2.0 6 votes vote down vote up
private Client initTransportClient() throws UnknownHostException {
    TransportClient client = null;
    try {
        Settings settings = Settings.builder()
                                    .put("cluster.name", "docker-node")
                                    .put("client.transport.sniff", false)
                                    .build();

        client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress
            .getByName(host), 9300));
    } catch (UnknownHostException e) {
        logger.error("create client error", e);
        throw e;
    }
    return client;
}
 
Example #15
Source Project: test-data-generator   Author: presidentio   File: AbstractEsSink.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init(Map<String, String> props) {
    String host = props.get(PropConst.HOST);
    if (host == null) {
        throw new IllegalArgumentException("Host does not specified");
    }
    String port = props.get(PropConst.PORT);
    if (port == null) {
        throw new IllegalArgumentException("Port does not specified");
    }
    String clusterName = props.get(PropConst.CLUSTER_NAME);
    if (clusterName == null) {
        throw new IllegalArgumentException("Cluster name does not specified");
    }
    client = (new TransportClient(ImmutableSettings.settingsBuilder().put("cluster.name", clusterName).build()))
            .addTransportAddress(new InetSocketTransportAddress(host, Integer.valueOf(port)));
}
 
Example #16
Source Project: zeppelin   Author: apache   File: TransportBasedClient.java    License: Apache License 2.0 6 votes vote down vote up
public TransportBasedClient(Properties props) throws UnknownHostException {
  final String host =
      props.getProperty(ElasticsearchInterpreter.ELASTICSEARCH_HOST);
  final int port = Integer.parseInt(
      props.getProperty(ElasticsearchInterpreter.ELASTICSEARCH_PORT));
  final String clusterName =
      props.getProperty(ElasticsearchInterpreter.ELASTICSEARCH_CLUSTER_NAME);

  final Settings settings = Settings.settingsBuilder()
      .put("cluster.name", clusterName)
      .put(props)
      .build();

  client = TransportClient.builder().settings(settings).build()
      .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
}
 
Example #17
Source Project: elasticshell   Author: javanna   File: DefaultClientFactory.java    License: Apache License 2.0 6 votes vote down vote up
protected ShellNativeClient newTransportClient(TransportAddress... addresses) {

        Settings settings = ImmutableSettings.settingsBuilder().put("client.transport.ignore_cluster_name", true).build();
        org.elasticsearch.client.transport.TransportClient client = new TransportClient(settings).addTransportAddresses(addresses);

        //if no connected node we can already close the (useless) client
        if (client.connectedNodes().size() == 0) {
            client.close();
            return null;
        }

        AbstractClient<TransportClient, JsonInput, JsonOutput> shellClient = clientWrapper.wrapEsTransportClient(client);
        resourceRegistry.registerResource(shellClient);
        ShellNativeClient shellNativeClient = clientWrapper.wrapShellClient(shellClient);
        clientScopeSynchronizerRunner.startSynchronizer(shellNativeClient);
        return shellNativeClient;
    }
 
Example #18
Source Project: rdf4j   Author: eclipse   File: InferenceTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String[] getIndexes() {

		Settings settings = Settings.builder().put("cluster.name", "cluster1").build();
		try (TransportClient client = new PreBuiltTransportClient(settings)) {
			client.addTransportAddress(
					new TransportAddress(InetAddress.getByName("localhost"), embeddedElastic.getTransportTcpPort()));

			return client.admin()
					.indices()
					.getIndex(new GetIndexRequest())
					.actionGet()
					.getIndices();
		} catch (UnknownHostException e) {
			throw new IllegalStateException(e);
		}

	}
 
Example #19
Source Project: localization_nifi   Author: wangrenlei   File: TestFetchElasticsearch.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected TransportClient getTransportClient(Settings.Builder settingsBuilder, String shieldUrl,
                                             String username, String password)
        throws MalformedURLException {
    TransportClient mockClient = mock(TransportClient.class);
    GetRequestBuilder getRequestBuilder = spy(new GetRequestBuilder(mockClient, GetAction.INSTANCE));
    if (exceptionToThrow != null) {
        doThrow(exceptionToThrow).when(getRequestBuilder).execute();
    } else {
        doReturn(new MockGetRequestBuilderExecutor(documentExists)).when(getRequestBuilder).execute();
    }
    when(mockClient.prepareGet(anyString(), anyString(), anyString())).thenReturn(getRequestBuilder);

    return mockClient;
}
 
Example #20
Source Project: AsuraFramework   Author: AsuraTeam   File: EsDoc.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 保存文档
 * @param indexName
 * @param indexType
 * @param obj
 * @return
 */
public boolean  saveOrUpdateDocument(String indexName, String indexType,String id,Object obj) {
    TransportClient client = esClientFactory.getClient();
    if(Check.NuNStrStrict(id)){
        logger.error("保存文档失败","id为空,请传id");
        return false;
    }
    IndexResponse indexResponse = client.prepareIndex(esClientFactory.getIndexs(indexName),indexType).setId(id).
                setSource(JSON.toJSONString(obj)).execute().actionGet();
    return true;
}
 
Example #21
Source Project: glowroot   Author: glowroot   File: ElasticsearchWrapper.java    License: Apache License 2.0 5 votes vote down vote up
private static void waitForElasticsearch() throws Exception {
    TransportClient client = Util.client(new InetSocketAddress("127.0.0.1", 9300));
    while (client.connectedNodes().isEmpty()) {
        SECONDS.sleep(1);
    }
    client.close();
}
 
Example #22
Source Project: AsuraFramework   Author: AsuraTeam   File: EsIndex.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 创建索引
 *
 * @param indexName
 *
 * @return
 */
public boolean createIndex(String indexName) {
    TransportClient client = esClientFactory.getClient();
    CreateIndexResponse response = null;
    // 如果存在返回true
    if (client.admin().indices().prepareExists(esClientFactory.getIndexs(indexName)).get().isExists()) {
        return true;
    } else {
        response = client.admin().indices().prepareCreate(esClientFactory.getIndexs(indexName)).execute().actionGet();
    }
    return response.isAcknowledged();
}
 
Example #23
Source Project: flink   Author: apache   File: ElasticsearchSinkITCase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected ElasticsearchSinkBase<Tuple2<Integer, String>, TransportClient> createElasticsearchSinkForNode(
		int bulkFlushMaxActions,
		String clusterName,
		ElasticsearchSinkFunction<Tuple2<Integer, String>> elasticsearchSinkFunction,
		String ipAddress) throws Exception {

	List<InetSocketAddress> transports = new ArrayList<>();
	transports.add(new InetSocketAddress(InetAddress.getByName(ipAddress), 9300));

	return new ElasticsearchSink<>(
			Collections.unmodifiableMap(createUserConfig(bulkFlushMaxActions, clusterName)),
			transports,
			elasticsearchSinkFunction);
}
 
Example #24
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: AdminOperationsTest.java    License: Apache License 2.0 5 votes vote down vote up
private IndicesAdminClient mockedIndicesAdminClient(BulkProcessorObjectFactory factory) {
    ClientProvider clientProvider = mock(ClientProvider.class);
    when(factory.getClientProvider()).thenReturn(clientProvider);

    TransportClient transportClient = PowerMockito.mock(TransportClient.class);
    when(clientProvider.createClient()).thenReturn(transportClient);

    AdminClient adminClient = mock(AdminClient.class);
    when(transportClient.admin()).thenReturn(adminClient);

    IndicesAdminClient indicesAdminClient = mock(IndicesAdminClient.class);
    when(adminClient.indices()).thenReturn(indicesAdminClient);

    return indicesAdminClient;
}
 
Example #25
Source Project: syncer   Author: zzt93   File: ElasticsearchChannel.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ThreadSafe(safe = {TransportClient.class, BatchBuffer.class})
@Override
public boolean flushIfReachSizeLimit() throws InterruptedException {
  List<SyncWrapper<WriteRequest>> aim = batchBuffer.flushIfReachSizeLimit();
  buildSendProcess(aim);
  return aim != null;
}
 
Example #26
Source Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: CustomFieldMaskedTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void populateData(TransportClient tc) {

        tc.index(new IndexRequest("deals").type("deals").id("0").setRefreshPolicy(RefreshPolicy.IMMEDIATE)
                .source("{\"customer\": {\"name\":\"cust1\", \"street\":\"testroad\"}, \"ip_source\": \"100.100.1.1\",\"ip_dest\": \"123.123.1.1\",\"amount\": 10, \"mynum\": 1000000000000000000}", XContentType.JSON)).actionGet();
        tc.index(new IndexRequest("deals").type("deals").id("2").setRefreshPolicy(RefreshPolicy.IMMEDIATE)
                .source("{\"customer\": {\"name\":\"cust2\", \"street\":\"testroad\"}, \"ip_source\": \"100.100.2.2\",\"ip_dest\": \"123.123.2.2\",\"amount\": 20, \"mynum\": 1000000000000000000}", XContentType.JSON)).actionGet();


        for (int i=0; i<30;i++) {
            tc.index(new IndexRequest("deals").type("deals").id("a"+i).setRefreshPolicy(RefreshPolicy.IMMEDIATE)
                    .source("{\"customer\": {\"name\":\"cust1\", \"street\":\"testroad\"}, \"ip_source\": \"200.100.1.1\",\"ip_dest\": \"123.123.1.1\",\"amount\": 10, \"mynum\": 1000000000000000000}", XContentType.JSON)).actionGet();
        }

     }
 
Example #27
Source Project: streams   Author: apache   File: ElasticsearchClientManager.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void start() {

    try {
      // We are currently using lazy loading to start the elasticsearch cluster, however.
      LOGGER.info("Creating a new TransportClient: {}", this.config.getHosts());

      Settings settings = Settings.settingsBuilder()
          .put("cluster.name", this.config.getClusterName())
          .put("client.transport.ping_timeout", "90s")
          .put("client.transport.nodes_sampler_interval", "60s")
          .build();

      // Create the client
      client = TransportClient.builder().settings(settings).build();
      for (String h : config.getHosts()) {
        LOGGER.info("Adding Host: {}", h);
        InetAddress address;

        if ( InetAddresses.isInetAddress(h)) {
          LOGGER.info("{} is an IP address", h);
          address = InetAddresses.forString(h);
        } else {
          LOGGER.info("{} is a hostname", h);
          address = InetAddress.getByName(h);
        }
        client.addTransportAddress(
            new InetSocketTransportAddress(
                address,
                config.getPort().intValue()));
      }
    } catch (Exception ex) {
      LOGGER.error("Could not Create elasticsearch Transport Client: {}", ex);
    }

  }
 
Example #28
Source Project: log4j2-elasticsearch   Author: rfoltyns   File: BulkProcessorObjectFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void failoverIsExecutedAfterNonSuccessfulRequest() {

    // given
    Builder builder = createTestObjectFactoryBuilder();
    ClientObjectFactory<TransportClient, BulkRequest> config = spy(builder.build());

    FailoverPolicy failoverPolicy = spy(new NoopFailoverPolicy());
    Function handler = spy(config.createFailureHandler(failoverPolicy));
    when(config.createFailureHandler(any())).thenReturn(handler);

    Settings settings = Settings.builder().build();
    TransportClient client = spy(new PreBuiltTransportClient(settings));
    client.addTransportAddress(new TransportAddress(new InetSocketAddress(9999)));
    when(config.createClient()).thenReturn(client);

    BulkProcessorFactory bulkProcessorFactory = new BulkProcessorFactory();
    BatchEmitter batchEmitter = bulkProcessorFactory.createInstance(
            1,
            100,
            config,
            failoverPolicy);

    String payload1 = "test1";
    ActionRequest testRequest = createTestRequest(payload1);

    // when
    batchEmitter.add(testRequest);

    // then
    ArgumentCaptor<BulkRequest> captor = ArgumentCaptor.forClass(BulkRequest.class);
    verify(handler, times(1)).apply(captor.capture());

    assertEquals(payload1, new BulkRequestIntrospector().items(captor.getValue()).iterator().next());
}
 
Example #29
Source Project: emotional_analysis   Author: 20100507   File: ESClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static TransportClient getClient() {
	Settings settings = Settings.settingsBuilder().put("client.transport.ignore_cluster_name", true)
			.build();
	client = TransportClient.builder().settings(settings).build()
			.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("192.168.254.129", 9300)));
	return client;
}
 
Example #30
Source Project: AsuraFramework   Author: AsuraTeam   File: EsIndex.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 检查索引是否存在
 * @param indexs
 * @return
 */
public boolean checkIndex(String ...indexs) {
    TransportClient client = esClientFactory.getClient();
    // 如果存在返回true
    if (client.admin().indices().prepareExists(esClientFactory.getIndexs(indexs)).get().isExists()) {
        return true;
    }
    return false;
}