Search in sources :

Example 6 with PreBuiltTransportClient

use of org.elasticsearch.transport.client.PreBuiltTransportClient in project nifi by apache.

the class AbstractElasticsearch5TransportClientProcessor method getTransportClient.

protected Client getTransportClient(Settings.Builder settingsBuilder, String xPackPath, String username, String password, List<InetSocketAddress> esHosts, ComponentLog log) throws MalformedURLException {
    // Map of headers
    Map<String, String> headers = new HashMap<>();
    TransportClient transportClient = null;
    // authorization token if username and password are supplied.
    if (!StringUtils.isBlank(xPackPath)) {
        ClassLoader xPackClassloader = Thread.currentThread().getContextClassLoader();
        try {
            // Get the plugin class
            Class xPackTransportClientClass = Class.forName("org.elasticsearch.xpack.client.PreBuiltXPackTransportClient", true, xPackClassloader);
            Constructor<?> ctor = xPackTransportClientClass.getConstructor(Settings.class, Class[].class);
            if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
                // Need a couple of classes from the X-Path Transport JAR to build the token
                Class usernamePasswordTokenClass = Class.forName("org.elasticsearch.xpack.security.authc.support.UsernamePasswordToken", true, xPackClassloader);
                Class securedStringClass = Class.forName("org.elasticsearch.xpack.security.authc.support.SecuredString", true, xPackClassloader);
                Constructor<?> securedStringCtor = securedStringClass.getConstructor(char[].class);
                Object securePasswordString = securedStringCtor.newInstance(password.toCharArray());
                Method basicAuthHeaderValue = usernamePasswordTokenClass.getMethod("basicAuthHeaderValue", String.class, securedStringClass);
                String authToken = (String) basicAuthHeaderValue.invoke(null, username, securePasswordString);
                if (authToken != null) {
                    headers.put("Authorization", authToken);
                }
                transportClient = (TransportClient) ctor.newInstance(settingsBuilder.build(), new Class[0]);
            }
        } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException xPackLoadException) {
            throw new ProcessException("X-Pack plugin could not be loaded and/or configured", xPackLoadException);
        }
    } else {
        getLogger().debug("No X-Pack Transport location specified, secure connections and/or authorization will not be available");
    }
    // (which is logged), so continue with a non-secure client
    if (transportClient == null) {
        transportClient = new PreBuiltTransportClient(settingsBuilder.build());
    }
    if (esHosts != null) {
        for (final InetSocketAddress host : esHosts) {
            try {
                transportClient.addTransportAddress(new InetSocketTransportAddress(host));
            } catch (IllegalArgumentException iae) {
                log.error("Could not add transport address {}", new Object[] { host });
            }
        }
    }
    Client client = transportClient.filterWithHeader(headers);
    return client;
}
Also used : TransportClient(org.elasticsearch.client.transport.TransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) Method(java.lang.reflect.Method) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) InvocationTargetException(java.lang.reflect.InvocationTargetException) ProcessException(org.apache.nifi.processor.exception.ProcessException) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) Client(org.elasticsearch.client.Client) TransportClient(org.elasticsearch.client.transport.TransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient)

Example 7 with PreBuiltTransportClient

use of org.elasticsearch.transport.client.PreBuiltTransportClient in project fess by codelibs.

the class EsDataStoreImpl method storeData.

@Override
protected void storeData(final DataConfig dataConfig, final IndexUpdateCallback callback, final Map<String, String> paramMap, final Map<String, String> scriptMap, final Map<String, Object> defaultDataMap) {
    final String hostsStr = paramMap.get(HOSTS);
    if (StringUtil.isBlank(hostsStr)) {
        logger.info("hosts is empty.");
        return;
    }
    final long readInterval = getReadInterval(paramMap);
    final Settings settings = Settings.builder().put(paramMap.entrySet().stream().filter(e -> e.getKey().startsWith(SETTINGS_PREFIX)).collect(Collectors.toMap(e -> e.getKey().replaceFirst("^settings\\.", StringUtil.EMPTY), e -> e.getValue()))).build();
    logger.info("Connecting to " + hostsStr + " with [" + settings.toDelimitedString(',') + "]");
    final InetSocketTransportAddress[] addresses = split(hostsStr, ",").get(stream -> stream.map(h -> {
        final String[] values = h.trim().split(":");
        try {
            if (values.length == 1) {
                return new InetSocketTransportAddress(InetAddress.getByName(values[0]), 9300);
            } else if (values.length == 2) {
                return new InetSocketTransportAddress(InetAddress.getByName(values[0]), Integer.parseInt(values[1]));
            }
        } catch (final Exception e) {
            logger.warn("Failed to parse address: " + h, e);
        }
        return null;
    }).filter(v -> v != null).toArray(n -> new InetSocketTransportAddress[n]));
    try (PreBuiltTransportClient client = new PreBuiltTransportClient(settings)) {
        client.addTransportAddresses(addresses);
        processData(dataConfig, callback, paramMap, scriptMap, defaultDataMap, readInterval, client);
    }
}
Also used : CrawlingAccessException(org.codelibs.fess.crawler.exception.CrawlingAccessException) Constants(org.codelibs.fess.Constants) MultipleCrawlingAccessException(org.codelibs.fess.crawler.exception.MultipleCrawlingAccessException) SearchHits(org.elasticsearch.search.SearchHits) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) IndexUpdateCallback(org.codelibs.fess.ds.IndexUpdateCallback) QueryBuilders(org.elasticsearch.index.query.QueryBuilders) InetAddress(java.net.InetAddress) LinkedHashMap(java.util.LinkedHashMap) StreamUtil.split(org.codelibs.core.stream.StreamUtil.split) Settings(org.elasticsearch.common.settings.Settings) Map(java.util.Map) SearchResponse(org.elasticsearch.action.search.SearchResponse) DataConfig(org.codelibs.fess.es.config.exentity.DataConfig) SearchHit(org.elasticsearch.search.SearchHit) DataStoreCrawlingException(org.codelibs.fess.exception.DataStoreCrawlingException) Logger(org.slf4j.Logger) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) Client(org.elasticsearch.client.Client) StringUtil(org.codelibs.core.lang.StringUtil) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) DataStoreException(org.codelibs.fess.exception.DataStoreException) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) Collectors(java.util.stream.Collectors) ComponentUtil(org.codelibs.fess.util.ComponentUtil) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) FailureUrlService(org.codelibs.fess.app.service.FailureUrlService) BulkRequestBuilder(org.elasticsearch.action.bulk.BulkRequestBuilder) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) Settings(org.elasticsearch.common.settings.Settings) CrawlingAccessException(org.codelibs.fess.crawler.exception.CrawlingAccessException) MultipleCrawlingAccessException(org.codelibs.fess.crawler.exception.MultipleCrawlingAccessException) DataStoreCrawlingException(org.codelibs.fess.exception.DataStoreCrawlingException) DataStoreException(org.codelibs.fess.exception.DataStoreException)

Example 8 with PreBuiltTransportClient

use of org.elasticsearch.transport.client.PreBuiltTransportClient in project metron by apache.

the class ElasticsearchUtils method getClient.

public static TransportClient getClient(Map<String, Object> globalConfiguration, Map<String, String> optionalSettings) {
    Settings.Builder settingsBuilder = Settings.builder();
    settingsBuilder.put("cluster.name", globalConfiguration.get("es.clustername"));
    settingsBuilder.put("client.transport.ping_timeout", "500s");
    if (optionalSettings != null) {
        settingsBuilder.put(optionalSettings);
    }
    Settings settings = settingsBuilder.build();
    TransportClient client;
    try {
        LOG.info("Number of available processors in Netty: {}", NettyRuntimeWrapper.availableProcessors());
        // Netty sets available processors statically and if an attempt is made to set it more than
        // once an IllegalStateException is thrown by NettyRuntime.setAvailableProcessors(NettyRuntime.java:87)
        // https://discuss.elastic.co/t/getting-availableprocessors-is-already-set-to-1-rejecting-1-illegalstateexception-exception/103082
        // https://discuss.elastic.co/t/elasticsearch-5-4-1-availableprocessors-is-already-set/88036
        System.setProperty("es.set.netty.runtime.available.processors", "false");
        client = new PreBuiltTransportClient(settings);
        for (HostnamePort hp : getIps(globalConfiguration)) {
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hp.hostname), hp.port));
        }
    } catch (UnknownHostException exception) {
        throw new RuntimeException(exception);
    }
    return client;
}
Also used : TransportClient(org.elasticsearch.client.transport.TransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) UnknownHostException(java.net.UnknownHostException) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) Settings(org.elasticsearch.common.settings.Settings)

Example 9 with PreBuiltTransportClient

use of org.elasticsearch.transport.client.PreBuiltTransportClient in project tutorials-java by Artister.

the class EsConfig method client.

@Bean
public TransportClient client() throws UnknownHostException {
    /*
            Dns地址
            InetAddress-->指向ES POST
            ES TCP 端口
         */
    InetSocketTransportAddress node = new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300);
    /*
            指定集群名称
         */
    Settings settings = Settings.builder().put("cluster.name", "ko").build();
    /*
           Settings.EMPTY ES client配置
         */
    TransportClient client = new PreBuiltTransportClient(settings);
    /*
            添加地址
            可以添加很多节点...
         */
    client.addTransportAddress(node);
    return client;
}
Also used : TransportClient(org.elasticsearch.client.transport.TransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) Settings(org.elasticsearch.common.settings.Settings) Bean(org.springframework.context.annotation.Bean)

Example 10 with PreBuiltTransportClient

use of org.elasticsearch.transport.client.PreBuiltTransportClient in project core-ng-project by neowu.

the class ElasticSearchImpl method createClient.

protected Client createClient() {
    if (addresses.isEmpty())
        throw new Error("addresses must not be empty");
    StopWatch watch = new StopWatch();
    try {
        Settings.Builder settings = Settings.builder();
        settings.put(NetworkService.TCP_CONNECT_TIMEOUT.getKey(), new TimeValue(timeout.toMillis())).put(TransportClient.CLIENT_TRANSPORT_PING_TIMEOUT.getKey(), new TimeValue(timeout.toMillis())).put(TransportClient.CLIENT_TRANSPORT_PING_TIMEOUT.getKey(), new TimeValue(timeout.toMillis())).put(TransportClient.CLIENT_TRANSPORT_IGNORE_CLUSTER_NAME.getKey(), // refer to https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/transport-client.html
        "true");
        if (sniff) {
            settings.put(TransportClient.CLIENT_TRANSPORT_SNIFF.getKey(), true);
        }
        TransportClient client = new PreBuiltTransportClient(settings.build());
        addresses.forEach(client::addTransportAddress);
        return client;
    } finally {
        logger.info("create elasticsearch client, addresses={}, elapsedTime={}", addresses, watch.elapsedTime());
    }
}
Also used : TransportClient(org.elasticsearch.client.transport.TransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) PreBuiltTransportClient(org.elasticsearch.transport.client.PreBuiltTransportClient) Settings(org.elasticsearch.common.settings.Settings) TimeValue(org.elasticsearch.common.unit.TimeValue) StopWatch(core.framework.util.StopWatch)

Aggregations

PreBuiltTransportClient (org.elasticsearch.transport.client.PreBuiltTransportClient)41 Settings (org.elasticsearch.common.settings.Settings)33 TransportClient (org.elasticsearch.client.transport.TransportClient)25 InetSocketTransportAddress (org.elasticsearch.common.transport.InetSocketTransportAddress)23 TransportAddress (org.elasticsearch.common.transport.TransportAddress)17 UnknownHostException (java.net.UnknownHostException)10 InetSocketAddress (java.net.InetSocketAddress)5 InetAddress (java.net.InetAddress)4 HashMap (java.util.HashMap)4 PostConstruct (javax.annotation.PostConstruct)4 SearchItem (cn.exrick.manager.dto.front.SearchItem)3 IOException (java.io.IOException)3 BulkRequestBuilder (org.elasticsearch.action.bulk.BulkRequestBuilder)3 IndexResponse (org.elasticsearch.action.index.IndexResponse)3 Builder (org.elasticsearch.common.settings.Settings.Builder)3 XmallException (cn.exrick.common.exception.XmallException)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 Logger (org.apache.log4j.Logger)2 ElasticsearchClusterRunner (org.codelibs.elasticsearch.runner.ElasticsearchClusterRunner)2