Java Code Examples for org.elasticsearch.client.node.NodeClient

The following examples show how to use org.elasticsearch.client.node.NodeClient. 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: ES-Fastloader   Source File: AppendLuceneRestHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) {
    AppendLuceneRequest appendLuceneRequest = new AppendLuceneRequest();

    appendLuceneRequest.indexName = request.param(INDEX_NAME);
    appendLuceneRequest.uuid = request.param(UUID);
    appendLuceneRequest.shardId = Integer.valueOf(request.param(SHARD_ID));
    appendLuceneRequest.appendSegmentDirs = request.param(APPEND);
    appendLuceneRequest.primeKey = request.param(PRIMERKEY);

    // 跳转到AppendLuceneTransportAction.doExecute()
    return channel -> client.executeLocally(AppendLuceneAction.INSTANCE, appendLuceneRequest, new RestBuilderListener<AppendLuceneResponse>(channel) {
        @Override
        public RestResponse buildResponse(AppendLuceneResponse appendLuceneResponse, XContentBuilder builder) throws Exception {
            return new BytesRestResponse(RestStatus.OK, appendLuceneResponse.toXContent(builder, ToXContent.EMPTY_PARAMS));
        }
    });
}
 
Example 2
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    if (!EnabledSetting.isADPluginEnabled()) {
        throw new IllegalStateException(CommonErrorMessages.DISABLED_ERR_MSG);
    }

    String detectorId = request.param(DETECTOR_ID);

    return channel -> {
        logger.info("Delete anomaly detector {}", detectorId);
        handler
            .getDetectorJob(
                clusterService,
                client,
                detectorId,
                channel,
                () -> deleteAnomalyDetectorJobDoc(client, detectorId, channel)
            );
    };
}
 
Example 3
private void deleteAnomalyDetectorJobDoc(NodeClient client, String detectorId, RestChannel channel) {
    logger.info("Delete anomaly detector job {}", detectorId);
    DeleteRequest deleteRequest = new DeleteRequest(AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX, detectorId)
        .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
    client.delete(deleteRequest, ActionListener.wrap(response -> {
        if (response.getResult() == DocWriteResponse.Result.DELETED || response.getResult() == DocWriteResponse.Result.NOT_FOUND) {
            deleteAnomalyDetectorDoc(client, detectorId, channel);
        } else {
            logger.error("Fail to delete anomaly detector job {}", detectorId);
        }
    }, exception -> {
        if (exception instanceof IndexNotFoundException) {
            deleteAnomalyDetectorDoc(client, detectorId, channel);
        } else {
            logger.error("Failed to delete anomaly detector job", exception);
            try {
                channel.sendResponse(new BytesRestResponse(channel, exception));
            } catch (IOException e) {
                logger.error("Failed to send response of delete anomaly detector job exception", e);
            }
        }
    }));
}
 
Example 4
/**
 * Get detector job for update/delete AD job.
 * If AD job exist, will return error message; otherwise, execute function.
 *
 * @param clusterService ES cluster service
 * @param client ES node client
 * @param detectorId detector identifier
 * @param channel ES rest channel
 * @param function AD function
 */
public void getDetectorJob(
    ClusterService clusterService,
    NodeClient client,
    String detectorId,
    RestChannel channel,
    AnomalyDetectorFunction function
) {
    if (clusterService.state().metadata().indices().containsKey(ANOMALY_DETECTOR_JOB_INDEX)) {
        GetRequest request = new GetRequest(ANOMALY_DETECTOR_JOB_INDEX).id(detectorId);
        client.get(request, ActionListener.wrap(response -> onGetAdJobResponseForWrite(response, channel, function), exception -> {
            logger.error("Fail to get anomaly detector job: " + detectorId, exception);
            try {
                channel.sendResponse(new BytesRestResponse(channel, exception));
            } catch (IOException e) {
                logger.error("Fail to send exception" + detectorId, e);
            }
        }));
    } else {
        function.execute();
    }
}
 
Example 5
/**
 * Constructor function.
 *
 * @param clusterService          ClusterService
 * @param client                  ES node client that executes actions on the local node
 * @param channel                 ES channel used to construct bytes / builder based outputs, and send responses
 * @param anomalyDetectionIndices anomaly detector index manager
 * @param detectorId              detector identifier
 * @param seqNo                   sequence number of last modification
 * @param primaryTerm             primary term of last modification
 * @param refreshPolicy           refresh policy
 * @param requestTimeout          request time out configuration
 */
public IndexAnomalyDetectorJobActionHandler(
    ClusterService clusterService,
    NodeClient client,
    RestChannel channel,
    AnomalyDetectionIndices anomalyDetectionIndices,
    String detectorId,
    Long seqNo,
    Long primaryTerm,
    WriteRequest.RefreshPolicy refreshPolicy,
    TimeValue requestTimeout
) {
    super(client, channel);
    this.clusterService = clusterService;
    this.anomalyDetectionIndices = anomalyDetectionIndices;
    this.detectorId = detectorId;
    this.seqNo = seqNo;
    this.primaryTerm = primaryTerm;
    this.refreshPolicy = refreshPolicy;
    this.requestTimeout = requestTimeout;
}
 
Example 6
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    if (!EnabledSetting.isADPluginEnabled()) {
        throw new IllegalStateException(CommonErrorMessages.DISABLED_ERR_MSG);
    }
    String detectorId = request.param(DETECTOR_ID);
    String typesStr = request.param(TYPE);
    String rawPath = request.rawPath();
    if (!Strings.isEmpty(typesStr) || rawPath.endsWith(PROFILE) || rawPath.endsWith(PROFILE + "/")) {
        boolean all = request.paramAsBoolean("_all", false);
        return channel -> profileRunner
            .profile(detectorId, getProfileActionListener(channel, detectorId), getProfilesToCollect(typesStr, all));
    } else {
        boolean returnJob = request.paramAsBoolean("job", false);
        MultiGetRequest.Item adItem = new MultiGetRequest.Item(ANOMALY_DETECTORS_INDEX, detectorId)
            .version(RestActions.parseVersion(request));
        MultiGetRequest multiGetRequest = new MultiGetRequest().add(adItem);
        if (returnJob) {
            MultiGetRequest.Item adJobItem = new MultiGetRequest.Item(ANOMALY_DETECTOR_JOB_INDEX, detectorId)
                .version(RestActions.parseVersion(request));
            multiGetRequest.add(adJobItem);
        }

        return channel -> client.multiGet(multiGetRequest, onMultiGetResponse(channel, returnJob, detectorId));
    }
}
 
Example 7
Source Project: zentity   Source File: HomeAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) {

    Properties props = ZentityPlugin.properties();
    Boolean pretty = restRequest.paramAsBoolean("pretty", false);

    return channel -> {
        XContentBuilder content = XContentFactory.jsonBuilder();
        if (pretty)
            content.prettyPrint();
        content.startObject();
        content.field("name", props.getProperty("name"));
        content.field("description", props.getProperty("description"));
        content.field("website", props.getProperty("zentity.website"));
        content.startObject("version");
        content.field("zentity", props.getProperty("zentity.version"));
        content.field("elasticsearch", props.getProperty("elasticsearch.version"));
        content.endObject();
        content.endObject();
        channel.sendResponse(new BytesRestResponse(RestStatus.OK, content));
    };
}
 
Example 8
Source Project: zentity   Source File: SetupAction.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create the .zentity-models index.
 *
 * @param client           The client that will communicate with Elasticsearch.
 * @param numberOfShards   The value of index.number_of_shards.
 * @param numberOfReplicas The value of index.number_of_replicas.
 * @return
 */
public static CreateIndexResponse createIndex(NodeClient client, int numberOfShards, int numberOfReplicas) {
    // Elasticsearch 7.0.0+ removes mapping types
    Properties props = ZentityPlugin.properties();
    if (props.getProperty("elasticsearch.version").compareTo("7.") >= 0) {
        return client.admin().indices().prepareCreate(ModelsAction.INDEX_NAME)
            .setSettings(Settings.builder()
                    .put("index.number_of_shards", numberOfShards)
                    .put("index.number_of_replicas", numberOfReplicas)
            )
            .addMapping("doc", INDEX_MAPPING, XContentType.JSON)
            .get();
    } else {
        return client.admin().indices().prepareCreate(ModelsAction.INDEX_NAME)
            .setSettings(Settings.builder()
                    .put("index.number_of_shards", numberOfShards)
                    .put("index.number_of_replicas", numberOfReplicas)
            )
            .addMapping("doc", INDEX_MAPPING_ELASTICSEARCH_6, XContentType.JSON)
            .get();
    }
}
 
Example 9
private RestChannelConsumer clearCache(RestRequest request, NodeClient client) {
    String storeName = indexName(request);
    ClearCachesAction.ClearCachesNodesRequest cacheRequest = new ClearCachesAction.ClearCachesNodesRequest();
    cacheRequest.clearStore(storeName);
    return (channel) -> client.execute(ClearCachesAction.INSTANCE, cacheRequest,
        new RestBuilderListener<ClearCachesNodesResponse>(channel) {
            @Override
            public RestResponse buildResponse(ClearCachesNodesResponse clearCachesNodesResponse,
                                              XContentBuilder builder) throws Exception {
                builder.startObject()
                        .field("acknowledged", true);
                builder.endObject();
                return new BytesRestResponse(OK, builder);
            }
        }
    );
}
 
Example 10
/**
 * Prepare the request for execution. Implementations should consume all request params before
 * returning the runnable for actual execution. Unconsumed params will immediately terminate
 * execution of the request. However, some params are only used in processing the response;
 * implementations can override {@link BaseRestHandler#responseParams()} to indicate such
 * params.
 *
 * @param request the request to execute
 * @param client  client for executing actions on the local node
 * @return the action to execute
 * @throws IOException if an I/O exception occurred parsing the request and preparing for
 *                     execution
 */
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    String indexName = indexName(request);
    if (request.method() == RestRequest.Method.PUT) {
        if (request.hasParam("store")) {
            IndexFeatureStore.validateFeatureStoreName(request.param("store"));
        }
        return createIndex(client, indexName);
    } else if (request.method() == RestRequest.Method.POST ) {
        if (request.hasParam("store")) {
            IndexFeatureStore.validateFeatureStoreName(request.param("store"));
        }
        throw new IllegalArgumentException("Updating a feature store is not yet supported.");
    } else if (request.method() == RestRequest.Method.DELETE) {
        return deleteIndex(client, indexName);
    } else {
        assert request.method() == RestRequest.Method.GET;
        // XXX: ambiguous api
        if (request.hasParam("store")) {
            return getStore(client, indexName);
        }
        return listStores(client);
    }
}
 
Example 11
Source Project: ranger   Source File: RangerSecurityRestFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final NodeClient client)
		throws Exception {
	// Now only support to get user from request,
	// it should work with other elasticsearch identity authentication plugins in fact.
	UsernamePasswordToken user = UsernamePasswordToken.parseToken(request);
	if (user == null) {
		throw new ElasticsearchStatusException("Error: User is null, the request requires user authentication.",
				RestStatus.UNAUTHORIZED);
	} else {
		if (LOG.isDebugEnabled()) {
			LOG.debug("Success to parse user[{}] from request[{}].", user, request);
		}
	}
	threadContext.putTransient(UsernamePasswordToken.USERNAME, user.getUsername());

	String clientIPAddress = RequestUtils.getClientIPAddress(request);
	if (StringUtils.isNotEmpty(clientIPAddress)) {
		threadContext.putTransient(RequestUtils.CLIENT_IP_ADDRESS, clientIPAddress);
	}

	this.restHandler.handleRequest(request, channel, client);
}
 
Example 12
Source Project: elasticsearch-sql   Source File: Test.java    License: Apache License 2.0 6 votes vote down vote up
public static String sqlToEsQuery(String sql) throws Exception {
        Map actions = new HashMap();
        Settings settings = Settings.builder().build();
//        Client client = new NodeClient(settings, null, null, actions);
//        Settings.builder()
//                .put(ThreadContext.PREFIX + ".key1", "val1")
//                .put(ThreadContext.PREFIX + ".key2", "val 2")
//                .build();

        ThreadPool threadPool = new ThreadPool(settings);
        Client client = new NodeClient(settings, threadPool);
        SearchDao searchDao = new org.nlpcn.es4sql.SearchDao(client);
        try {
            return searchDao.explain(sql).explain().explain();
        } catch (Exception e) {
            throw e;
        }
    }
 
Example 13
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    final LangdetectRequest langdetectRequest = new LangdetectRequest();
    langdetectRequest.setText(request.param("text"));
    langdetectRequest.setProfile(request.param("profile", ""));
    withContent(request, parser -> {
        if (parser != null) {
            XContentParser.Token token;
            while ((token = parser.nextToken()) != null) {
                if (token == XContentParser.Token.VALUE_STRING) {
                    if ("text".equals(parser.currentName())) {
                        langdetectRequest.setText(parser.text());
                    } else if ("profile".equals(parser.currentName())) {
                        langdetectRequest.setProfile(parser.text());
                    }
                }
            }
        }
    });
    return channel -> client.execute(LangdetectAction.INSTANCE, langdetectRequest,
            new RestStatusToXContentListener<>(channel));
}
 
Example 14
Source Project: crate   Source File: Netty4Plugin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Supplier<HttpServerTransport>> getHttpTransports(Settings settings, ThreadPool threadPool, BigArrays bigArrays,
                                                                    CircuitBreakerService circuitBreakerService,
                                                                    NamedWriteableRegistry namedWriteableRegistry,
                                                                    NamedXContentRegistry xContentRegistry,
                                                                    NetworkService networkService,
                                                                    NodeClient nodeClient) {
    return Collections.singletonMap(
        NETTY_HTTP_TRANSPORT_NAME,
        () -> new Netty4HttpServerTransport(
            settings,
            networkService,
            bigArrays,
            threadPool,
            xContentRegistry,
            pipelineRegistry,
            nodeClient
        )
    );
}
 
Example 15
Source Project: crate   Source File: InternalClusterInfoService.java    License: Apache License 2.0 6 votes vote down vote up
public InternalClusterInfoService(Settings settings, ClusterService clusterService, ThreadPool threadPool, NodeClient client) {
    this.leastAvailableSpaceUsages = ImmutableOpenMap.of();
    this.mostAvailableSpaceUsages = ImmutableOpenMap.of();
    this.shardRoutingToDataPath = ImmutableOpenMap.of();
    this.shardSizes = ImmutableOpenMap.of();
    this.clusterService = clusterService;
    this.threadPool = threadPool;
    this.client = client;
    this.updateFrequency = INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL_SETTING.get(settings);
    this.fetchTimeout = INTERNAL_CLUSTER_INFO_TIMEOUT_SETTING.get(settings);
    this.enabled = DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED_SETTING.get(settings);
    ClusterSettings clusterSettings = clusterService.getClusterSettings();
    //clusterSettings.addSettingsUpdateConsumer(INTERNAL_CLUSTER_INFO_TIMEOUT_SETTING, this::setFetchTimeout);
    //clusterSettings.addSettingsUpdateConsumer(INTERNAL_CLUSTER_INFO_UPDATE_INTERVAL_SETTING, this::setUpdateFrequency);
    clusterSettings.addSettingsUpdateConsumer(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED_SETTING, this::setEnabled);

    // Add InternalClusterInfoService to listen for Master changes
    this.clusterService.addLocalNodeMasterListener(this);
    // Add to listen for state changes (when nodes are added)
    this.clusterService.addListener(this);
}
 
Example 16
Source Project: crate   Source File: TransportSchemaUpdateAction.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
public TransportSchemaUpdateAction(TransportService transportService,
                                   ClusterService clusterService,
                                   ThreadPool threadPool,
                                   IndexNameExpressionResolver indexNameExpressionResolver,
                                   NodeClient nodeClient,
                                   NamedXContentRegistry xContentRegistry) {
    super(
        "internal:crate:sql/ddl/schema_update",
        transportService,
        clusterService,
        threadPool,
        SchemaUpdateRequest::new,
        indexNameExpressionResolver
    );
    this.nodeClient = nodeClient;
    this.xContentRegistry = xContentRegistry;
}
 
Example 17
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
	switch (request.method()) {
	case GET:
		return handleGet(request, client);
	default:
		throw new IllegalArgumentException(request.method() + " not supported");
	}
}
 
Example 18
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    if (!EnabledSetting.isADPluginEnabled()) {
        throw new IllegalStateException(CommonErrorMessages.DISABLED_ERR_MSG);
    }

    String detectorId = request.param(DETECTOR_ID);

    return channel -> {
        long seqNo = request.paramAsLong(IF_SEQ_NO, SequenceNumbers.UNASSIGNED_SEQ_NO);
        long primaryTerm = request.paramAsLong(IF_PRIMARY_TERM, SequenceNumbers.UNASSIGNED_PRIMARY_TERM);
        WriteRequest.RefreshPolicy refreshPolicy = request.hasParam(REFRESH)
            ? WriteRequest.RefreshPolicy.parse(request.param(REFRESH))
            : WriteRequest.RefreshPolicy.IMMEDIATE;

        IndexAnomalyDetectorJobActionHandler handler = new IndexAnomalyDetectorJobActionHandler(
            clusterService,
            client,
            channel,
            anomalyDetectionIndices,
            detectorId,
            seqNo,
            primaryTerm,
            refreshPolicy,
            requestTimeout
        );

        String rawPath = request.rawPath();

        if (rawPath.endsWith(START_JOB)) {
            handler.startAnomalyDetectorJob();
        } else if (rawPath.endsWith(STOP_JOB)) {
            handler.stopAnomalyDetectorJob(detectorId);
        }
    };
}
 
Example 19
private void preivewAnomalyDetector(NodeClient client, RestChannel channel, AnomalyDetectorExecutionInput input) {
    if (!StringUtils.isBlank(input.getDetectorId())) {
        GetRequest getRequest = new GetRequest(AnomalyDetector.ANOMALY_DETECTORS_INDEX).id(input.getDetectorId());
        client.get(getRequest, onGetAnomalyDetectorResponse(channel, input));
    } else {
        channel.sendResponse(new BytesRestResponse(RestStatus.NOT_FOUND, "Wrong input, no detector id"));
    }
}
 
Example 20
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    if (!EnabledSetting.isADPluginEnabled()) {
        throw new IllegalStateException(CommonErrorMessages.DISABLED_ERR_MSG);
    }

    String detectorId = request.param(DETECTOR_ID, AnomalyDetector.NO_ID);
    logger.info("AnomalyDetector {} action for detectorId {}", request.method(), detectorId);

    XContentParser parser = request.contentParser();
    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
    // TODO: check detection interval < modelTTL
    AnomalyDetector detector = AnomalyDetector.parse(parser, detectorId, null, detectionInterval, detectionWindowDelay);

    long seqNo = request.paramAsLong(IF_SEQ_NO, SequenceNumbers.UNASSIGNED_SEQ_NO);
    long primaryTerm = request.paramAsLong(IF_PRIMARY_TERM, SequenceNumbers.UNASSIGNED_PRIMARY_TERM);
    WriteRequest.RefreshPolicy refreshPolicy = request.hasParam(REFRESH)
        ? WriteRequest.RefreshPolicy.parse(request.param(REFRESH))
        : WriteRequest.RefreshPolicy.IMMEDIATE;

    return channel -> new IndexAnomalyDetectorActionHandler(
        settings,
        clusterService,
        client,
        channel,
        anomalyDetectionIndices,
        detectorId,
        seqNo,
        primaryTerm,
        refreshPolicy,
        detector,
        requestTimeout,
        maxAnomalyDetectors,
        maxAnomalyFeatures
    ).start();
}
 
Example 21
/**
 * Constructor function.
 *
 * @param settings                ES settings
 * @param clusterService          ClusterService
 * @param client                  ES node client that executes actions on the local node
 * @param channel                 ES channel used to construct bytes / builder based outputs, and send responses
 * @param anomalyDetectionIndices anomaly detector index manager
 * @param detectorId              detector identifier
 * @param seqNo                   sequence number of last modification
 * @param primaryTerm             primary term of last modification
 * @param refreshPolicy           refresh policy
 * @param anomalyDetector         anomaly detector instance
 * @param requestTimeout          request time out configuration
 */
public IndexAnomalyDetectorActionHandler(
    Settings settings,
    ClusterService clusterService,
    NodeClient client,
    RestChannel channel,
    AnomalyDetectionIndices anomalyDetectionIndices,
    String detectorId,
    Long seqNo,
    Long primaryTerm,
    WriteRequest.RefreshPolicy refreshPolicy,
    AnomalyDetector anomalyDetector,
    TimeValue requestTimeout,
    Integer maxAnomalyDetectors,
    Integer maxAnomalyFeatures
) {
    super(client, channel);
    this.clusterService = clusterService;
    this.anomalyDetectionIndices = anomalyDetectionIndices;
    this.detectorId = detectorId;
    this.seqNo = seqNo;
    this.primaryTerm = primaryTerm;
    this.refreshPolicy = refreshPolicy;
    this.anomalyDetector = anomalyDetector;
    this.requestTimeout = requestTimeout;
    this.maxAnomalyDetectors = maxAnomalyDetectors;
    this.maxAnomalyFeatures = maxAnomalyFeatures;
}
 
Example 22
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) {
    if (!EnabledSetting.isADPluginEnabled()) {
        throw new IllegalStateException(CommonErrorMessages.DISABLED_ERR_MSG);
    }
    ADStatsRequest adStatsRequest = getRequest(request);
    return channel -> getStats(client, channel, adStatsRequest);
}
 
Example 23
Source Project: anomaly-detection   Source File: AbstractSearchAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
    if (!EnabledSetting.isADPluginEnabled()) {
        throw new IllegalStateException(CommonErrorMessages.DISABLED_ERR_MSG);
    }
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.parseXContent(request.contentOrSourceParamParser());
    searchSourceBuilder.fetchSource(getSourceContext(request));
    searchSourceBuilder.seqNoAndPrimaryTerm(true).version(true);
    SearchRequest searchRequest = new SearchRequest().source(searchSourceBuilder).indices(this.index);
    return channel -> client.search(searchRequest, search(channel, this.clazz));
}
 
Example 24
Source Project: zentity   Source File: ModelsAction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check if the .zentity-models index exists, and if it doesn't, then create it.
 *
 * @param client The client that will communicate with Elasticsearch.
 * @throws ForbiddenException
 */
public static void ensureIndex(NodeClient client) throws ForbiddenException {
    try {
        IndicesExistsRequestBuilder request = client.admin().indices().prepareExists(INDEX_NAME);
        IndicesExistsResponse response = request.get();
        if (!response.isExists())
            SetupAction.createIndex(client);
    } catch (ElasticsearchSecurityException se) {
        throw new ForbiddenException("The .zentity-models index does not exist and you do not have the 'create_index' privilege. An authorized user must create the index by submitting: POST _zentity/_setup");
    }
}
 
Example 25
Source Project: zentity   Source File: ModelsAction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve all entity models.
 *
 * @param client The client that will communicate with Elasticsearch.
 * @return The response from Elasticsearch.
 * @throws ForbiddenException
 */
public static SearchResponse getEntityModels(NodeClient client) throws ForbiddenException {
    SearchRequestBuilder request = client.prepareSearch(INDEX_NAME);
    request.setSize(10000);
    try {
        return request.get();
    } catch (IndexNotFoundException e) {
        try {
            SetupAction.createIndex(client);
        } catch (ElasticsearchSecurityException se) {
            throw new ForbiddenException("The .zentity-models index does not exist and you do not have the 'create_index' privilege. An authorized user must create the index by submitting: POST _zentity/_setup");
        }
        return request.get();
    }
}
 
Example 26
Source Project: zentity   Source File: ModelsAction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve one entity model by its type.
 *
 * @param entityType The entity type.
 * @param client     The client that will communicate with Elasticsearch.
 * @return The response from Elasticsearch.
 * @throws ForbiddenException
 */
public static GetResponse getEntityModel(String entityType, NodeClient client) throws ForbiddenException {
    GetRequestBuilder request = client.prepareGet(INDEX_NAME, "doc", entityType);
    try {
        return request.get();
    } catch (IndexNotFoundException e) {
        try {
            SetupAction.createIndex(client);
        } catch (ElasticsearchSecurityException se) {
            throw new ForbiddenException("The .zentity-models index does not exist and you do not have the 'create_index' privilege. An authorized user must create the index by submitting: POST _zentity/_setup");
        }
        return request.get();
    }
}
 
Example 27
Source Project: zentity   Source File: ModelsAction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Delete one entity model by its type.
 *
 * @param entityType The entity type.
 * @param client     The client that will communicate with Elasticsearch.
 * @return The response from Elasticsearch.
 * @throws ForbiddenException
 */
private static DeleteResponse deleteEntityModel(String entityType, NodeClient client) throws ForbiddenException {
    DeleteRequestBuilder request = client.prepareDelete(INDEX_NAME, "doc", entityType);
    request.setRefreshPolicy("wait_for");
    try {
        return request.get();
    } catch (IndexNotFoundException e) {
        try {
            SetupAction.createIndex(client);
        } catch (ElasticsearchSecurityException se) {
            throw new ForbiddenException("The .zentity-models index does not exist and you do not have the 'create_index' privilege. An authorized user must create the index by submitting: POST _zentity/_setup");
        }
        return request.get();
    }
}
 
Example 28
Source Project: zentity   Source File: SetupAction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) {

    // Parse request
    Boolean pretty = restRequest.paramAsBoolean("pretty", false);
    int numberOfShards = restRequest.paramAsInt("number_of_shards", 1);
    int numberOfReplicas = restRequest.paramAsInt("number_of_replicas", 1);
    Method method = restRequest.method();

    return channel -> {
        try {
            if (method == POST) {

                createIndex(client, numberOfShards, numberOfReplicas);
                XContentBuilder content = XContentFactory.jsonBuilder();
                if (pretty)
                    content.prettyPrint();
                content.startObject().field("acknowledged", true).endObject();
                channel.sendResponse(new BytesRestResponse(RestStatus.OK, content));

            } else {
                throw new NotImplementedException("Method and endpoint not implemented.");
            }
        } catch (NotImplementedException e) {
            channel.sendResponse(new BytesRestResponse(channel, RestStatus.NOT_IMPLEMENTED, e));
        }
    };
}
 
Example 29
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) {
    if (logger.isTraceEnabled()) {
        String remoteAddress = NetworkAddress.format(request.getHttpChannel().getRemoteAddress());
        logger.trace(String.format(Locale.ENGLISH, "Received request for Prometheus metrics from %s",
                remoteAddress));
    }

    NodePrometheusMetricsRequest metricsRequest = new NodePrometheusMetricsRequest();

    return channel -> client.execute(INSTANCE, metricsRequest,
            new RestResponseListener<NodePrometheusMetricsResponse>(channel) {

                @Override
                public RestResponse buildResponse(NodePrometheusMetricsResponse response) throws Exception {
            String clusterName = response.getClusterHealth().getClusterName();
            String nodeName = response.getNodeStats().getNode().getName();
            String nodeId = response.getNodeStats().getNode().getId();
            if (logger.isTraceEnabled()) {
                logger.trace("Prepare new Prometheus metric collector for: [{}], [{}], [{}]", clusterName, nodeId,
                        nodeName);
            }
            PrometheusMetricsCatalog catalog = new PrometheusMetricsCatalog(clusterName, nodeName, nodeId, "es_");
            PrometheusMetricsCollector collector = new PrometheusMetricsCollector(
                    catalog,
                    prometheusSettings.getPrometheusIndices(),
                    prometheusSettings.getPrometheusClusterSettings());
            collector.registerMetrics();
            collector.updateMetrics(response.getClusterHealth(), response.getNodeStats(), response.getIndicesStats(),
                    response.getClusterStatsData());
            return new BytesRestResponse(RestStatus.OK, collector.getCatalog().toTextFormat());
        }
    });
}
 
Example 30
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) {
    if (request.method() == RestRequest.Method.POST) {
        return clearCache(request, client);
    } else {
        return getStats(client);
    }
}