org.elasticsearch.rest.RestChannel Java Examples

The following examples show how to use org.elasticsearch.rest.RestChannel. 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: TasteActionRestAction.java    From elasticsearch-taste with Apache License 2.0 6 votes vote down vote up
private void sendResponse(final RestRequest request,
        final RestChannel channel, final Map<String, Object> params,
        final boolean acknowledged) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        if (request.hasParam("pretty")) {
            builder.prettyPrint().lfAtEnd();
        }
        builder.startObject();
        builder.field("acknowledged", acknowledged);
        if (params != null) {
            for (final Map.Entry<String, Object> entry : params.entrySet()) {
                builder.field(entry.getKey(), entry.getValue());
            }
        }
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final Exception e) {
        sendErrorResponse(channel, e);
    }
}
 
Example #2
Source File: AuthTokenProcessorHandler.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
boolean handle(RestRequest restRequest, RestChannel restChannel) throws Exception {
    try {
        final SecurityManager sm = System.getSecurityManager();

        if (sm != null) {
            sm.checkPermission(new SpecialPermission());
        }

        return AccessController.doPrivileged(new PrivilegedExceptionAction<Boolean>() {
            @Override
            public Boolean run() throws XPathExpressionException, SamlConfigException, IOException,
                    ParserConfigurationException, SAXException, SettingsException {
                return handleLowLevel(restRequest, restChannel);
            }
        });
    } catch (PrivilegedActionException e) {
        if (e.getCause() instanceof Exception) {
            throw (Exception) e.getCause();
        } else {
            throw new RuntimeException(e);
        }
    }
}
 
Example #3
Source File: ReloadRestAction.java    From elasticsearch-auth with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleRequest(final RestRequest request,
        final RestChannel channel, final Client client) {

    authService.reload(new ActionListener<Void>() {
        @Override
        public void onResponse(final Void response) {
            ResponseUtil.send(request, channel, RestStatus.OK);
        }

        @Override
        public void onFailure(final Throwable e) {
            ResponseUtil.send(request, channel,
                    RestStatus.INTERNAL_SERVER_ERROR, "message",
                    "Failed to reload AuthService.");
        }
    });
}
 
Example #4
Source File: IndexAnomalyDetectorJobActionHandler.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
private ActionListener<StopDetectorResponse> stopAdDetectorListener(RestChannel channel, String detectorId) {
    return new ActionListener<StopDetectorResponse>() {
        @Override
        public void onResponse(StopDetectorResponse stopDetectorResponse) {
            if (stopDetectorResponse.success()) {
                logger.info("AD model deleted successfully for detector {}", detectorId);
                channel.sendResponse(new BytesRestResponse(RestStatus.OK, "Stopped detector: " + detectorId));
            } else {
                logger.error("Failed to delete AD model for detector {}", detectorId);
                channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, "Failed to delete AD model"));
            }
        }

        @Override
        public void onFailure(Exception e) {
            logger.error("Failed to delete AD model for detector " + detectorId, e);
            channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, "Failed to execute stop detector action"));
        }
    };
}
 
Example #5
Source File: DynamicACLFilter.java    From openshift-elasticsearch-plugin with Apache License 2.0 6 votes vote down vote up
public RestRequest continueProcessing(RestRequest request, RestChannel channel) throws Exception {
    try {
        if (threadContext.getTransient(OPENSHIFT_REQUEST_CONTEXT) != null) {
            OpenshiftRequestContext requestContext = threadContext.getTransient(OPENSHIFT_REQUEST_CONTEXT);
            request = utils.modifyRequest(request, requestContext, channel);
            Boolean syncAndSeed = threadContext.getTransient(SYNC_AND_SEED);
            if (requestContext != OpenshiftRequestContext.EMPTY){
                if(Boolean.TRUE.equals(syncAndSeed)) {
                    LOGGER.debug("Seeding dashboards and syncing ACLs for user {}", requestContext.getUser());
                    utils.logRequest(request);
                    final String kbnVersion = getKibanaVersion(request);
                    kibanaSeed.setDashboards(requestContext, kbnVersion, cdmProjectPrefix);
                    aclManager.syncAcl(requestContext);
                } else {
                    LOGGER.debug("Cache hit. Skipping dashboards and syncing ACLs for user {}", requestContext.getUser());
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error handling request", e);
    }
    return request;
}
 
Example #6
Source File: AnomalyDetectorActionHandler.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
private void onGetAdJobResponseForWrite(GetResponse response, RestChannel channel, AnomalyDetectorFunction function) {
    if (response.isExists()) {
        String adJobId = response.getId();
        if (adJobId != null) {
            // check if AD job is running on the detector, if yes, we can't delete the detector
            try (XContentParser parser = RestHandlerUtils.createXContentParser(channel, response.getSourceAsBytesRef())) {
                ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
                AnomalyDetectorJob adJob = AnomalyDetectorJob.parse(parser);
                if (adJob.isEnabled()) {
                    channel.sendResponse(new BytesRestResponse(RestStatus.BAD_REQUEST, "Detector job is running: " + adJobId));
                    return;
                }
            } catch (IOException e) {
                String message = "Failed to parse anomaly detector job " + adJobId;
                logger.error(message, e);
                channel.sendResponse(new BytesRestResponse(RestStatus.BAD_REQUEST, message));
            }
        }
    }
    function.execute();
}
 
Example #7
Source File: AnomalyDetectorActionHandler.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #8
Source File: AuthRestFilter.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) {
    LoginUserContext user = null;
    request.putInContext(RestRequest.REQUEST_START_TIME, System.currentTimeMillis());
    try {
        user = new LoginUserContext(request, clusterService);
    } catch (NoPermissionException e) {
        logger.info("errors while parsing userinfo from request, error msg is [{}]", e.getMessage());
        ResponseUtil.send(channel, RestStatus.UNAUTHORIZED, e.getMessage());
        return;
    }

    if (user.loginUsername() == null || user.loginUsername().length() ==0) {
        ResponseUtil.send(channel, RestStatus.UNAUTHORIZED, "Username is empty");
        logger.info("Username is empty");
    }
    if (!user.authenticated() && (user.password() == null || user.password().length() ==0)) {
        ResponseUtil.send(channel, RestStatus.UNAUTHORIZED, "Password is empty");
        logger.info("Password is empty");
    }
    // put user info into context
    request.putHeader(LoginUserContext.USER_INFO_KEY, user);
    filterChain.continueProcessing(request, channel);
}
 
Example #9
Source File: RestDataAction.java    From elasticsearch-dataformat with Apache License 2.0 6 votes vote down vote up
private void sendResponse(final RestRequest request, final RestChannel channel, final String file) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        final String pretty = request.param("pretty");
        if (pretty != null && !"false".equalsIgnoreCase(pretty)) {
            builder.prettyPrint().lfAtEnd();
        }
        builder.startObject();
        builder.field("acknowledged", true);
        builder.field("file", file);
        builder.endObject();
        channel.sendResponse(new BytesRestResponse(OK, builder));
    } catch (final IOException e) {
        throw new ElasticsearchException("Failed to create a resposne.", e);
    }
}
 
Example #10
Source File: RestListTasksAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    boolean detailed = request.paramAsBoolean("detailed", false);
    String[] nodesIds = Strings.splitStringByCommaToArray(request.param("node_id"));
    TaskId taskId = new TaskId(request.param("taskId"));
    String[] actions = Strings.splitStringByCommaToArray(request.param("actions"));
    TaskId parentTaskId = new TaskId(request.param("parent_task_id"));
    boolean waitForCompletion = request.paramAsBoolean("wait_for_completion", false);
    TimeValue timeout = request.paramAsTime("timeout", null);

    ListTasksRequest listTasksRequest = new ListTasksRequest();
    listTasksRequest.setTaskId(taskId);
    listTasksRequest.setNodesIds(nodesIds);
    listTasksRequest.setDetailed(detailed);
    listTasksRequest.setActions(actions);
    listTasksRequest.setParentTaskId(parentTaskId);
    listTasksRequest.setWaitForCompletion(waitForCompletion);
    listTasksRequest.setTimeout(timeout);
    client.admin().cluster().listTasks(listTasksRequest, new RestToXContentListener<ListTasksResponse>(channel));
}
 
Example #11
Source File: RestDeleteAnomalyDetectorAction.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: ResponseUtil.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static void send(final RestChannel channel, final RestStatus status, final String message) {
    try {
        final XContentBuilder builder = JsonXContent.contentBuilder();
        builder.startObject()
                .field("status", status.getStatus())
                .field("message", message).endObject();
        BytesRestResponse bytesRestResponse = new BytesRestResponse(status, builder);
        if (status == RestStatus.UNAUTHORIZED) {
            bytesRestResponse.addHeader("WWW-authenticate", "Basic realm=\"Elasticsearch Authentication\"");
        }
        channel.sendResponse(bytesRestResponse);
    } catch (final IOException e) {
        logger.error("Failed to send a response.", e);
        try {
            channel.sendResponse(new BytesRestResponse(channel, e));
        } catch (final IOException e1) {
            logger.error("Failed to send a failure response.", e1);
        }
    }
}
 
Example #13
Source File: AbstractApiAction.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
protected void handleGet(final RestChannel channel, RestRequest request, Client client, final JsonNode content)
		throws IOException{

	final String resourcename = request.param("name");

	final SecurityDynamicConfiguration<?> configuration = load(getConfigName(), true);
	filter(configuration);


	// no specific resource requested, return complete config
	if (resourcename == null || resourcename.length() == 0) {

		successResponse(channel, configuration);
		return;
	}

	if (!configuration.exists(resourcename)) {
		notFound(channel, "Resource '" + resourcename + "' not found.");
		return;
	}

	configuration.removeOthers(resourcename);
	successResponse(channel, configuration);

	return;
}
 
Example #14
Source File: JobRestHandler.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
public void sendFailure(RestRequest request, RestChannel channel, Throwable e) {
	try {
		channel.sendResponse(new BytesRestResponse(channel, e));
	} catch (IOException e1) {
		logger.error("Failed to send failure response", e1);
	}
}
 
Example #15
Source File: CSVRestSearchAction.java    From elasticsearch-csv with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    SearchRequest searchRequest = RestSearchAction.parseSearchRequest(request);
    searchRequest.listenerThreaded(false);
    client.search(searchRequest, new CSVToXContentListener(channel,
            request.paramAsStringArray("keys", null),
            request.paramAsBoolean("with_index", false),
                    request.paramAsBoolean("with_type", false),
                    request.paramAsBoolean("with_id", false))
    );
}
 
Example #16
Source File: RestUpgradeAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
void handleGet(final RestRequest request, RestChannel channel, Client client) {
    client.admin().indices().prepareUpgradeStatus(Strings.splitStringByCommaToArray(request.param("index")))
            .execute(new RestBuilderListener<UpgradeStatusResponse>(channel) {
                @Override
                public RestResponse buildResponse(UpgradeStatusResponse response, XContentBuilder builder) throws Exception {
                    builder.startObject();
                    response.toXContent(builder, request);
                    builder.endObject();
                    return new BytesRestResponse(OK, builder);
                }
            });
}
 
Example #17
Source File: OpenDistroSecurityConfigAction.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Override
protected void handlePut(RestChannel channel, final RestRequest request, final Client client, final JsonNode content) throws IOException{
    if (allowPutOrPatch) {

        if(!"config".equals(request.param("name"))) {
            badRequestResponse(channel, "name must be config");
            return;
        }

        super.handlePut(channel, request, client, content);
    } else {
        notImplemented(channel, Method.PUT);
    }
}
 
Example #18
Source File: OpenDistroSecurityConfigAction.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleApiRequest(RestChannel channel, RestRequest request, Client client) throws IOException {
    if (request.method() == Method.PATCH && !allowPutOrPatch) {
        notImplemented(channel, Method.PATCH);
    } else {
        super.handleApiRequest(channel, request, client);
    }
}
 
Example #19
Source File: CommandRestHandler.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
public void SendFailure(RestRequest request, RestChannel channel,
		Throwable e) {
	try {
		channel.sendResponse(new BytesRestResponse(channel, e));
	} catch (IOException e1) {
		logger.error("Failed to send failure response", e1);
	}
}
 
Example #20
Source File: AbstractSearchAction.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private RestResponseListener<SearchResponse> search(RestChannel channel, Class<T> clazz) {
    return new RestResponseListener<SearchResponse>(channel) {
        @Override
        public RestResponse buildResponse(SearchResponse response) throws Exception {
            if (response.isTimedOut()) {
                return new BytesRestResponse(RestStatus.REQUEST_TIMEOUT, response.toString());
            }

            if (clazz == AnomalyDetector.class) {
                for (SearchHit hit : response.getHits()) {
                    XContentParser parser = XContentType.JSON
                        .xContent()
                        .createParser(
                            channel.request().getXContentRegistry(),
                            LoggingDeprecationHandler.INSTANCE,
                            hit.getSourceAsString()
                        );
                    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);

                    // write back id and version to anomaly detector object
                    ToXContentObject xContentObject = AnomalyDetector.parse(parser, hit.getId(), hit.getVersion());
                    XContentBuilder builder = xContentObject.toXContent(jsonBuilder(), EMPTY_PARAMS);
                    hit.sourceRef(BytesReference.bytes(builder));
                }
            }

            return new BytesRestResponse(RestStatus.OK, response.toXContent(channel.newBuilder(), EMPTY_PARAMS));
        }
    };
}
 
Example #21
Source File: FlushCacheApiAction.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleDelete(RestChannel channel,
        RestRequest request, Client client, final JsonNode content) throws IOException
{

	client.execute(
			ConfigUpdateAction.INSTANCE,
			new ConfigUpdateRequest(CType.lcStringValues().toArray(new String[0])),
			new ActionListener<ConfigUpdateResponse>() {

				@Override
				public void onResponse(ConfigUpdateResponse ur) {
				    if(ur.hasFailures()) {
				        log.error("Cannot flush cache due to", ur.failures().get(0));
                        internalErrorResponse(channel, "Cannot flush cache due to "+ ur.failures().get(0).getMessage()+".");
                        return;
                    }
					successResponse(channel, "Cache flushed successfully.");
					if (log.isDebugEnabled()) {
					    log.debug("cache flushed successfully");
					}
				}

				@Override
				public void onFailure(Exception e) {
				    log.error("Cannot flush cache due to", e);
					internalErrorResponse(channel, "Cannot flush cache due to "+ e.getMessage()+".");
				}

			}
	);
}
 
Example #22
Source File: JobRestHandler.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
private Search newSearchFromCommandString(String command, Client client, RestChannel channel, RestRequest request){
	
	try{
		CommandParser parser = new CommandParser(command);
		
		AST_Start.dumpWithLogger(logger, parser.getInnerTree(), "");
		
		return new Search(parser, client, logger);
	} catch (Exception e1) {
		sendFailure(request, channel, e1);
		return null;
	}
}
 
Example #23
Source File: LoggerUtils.java    From elasticsearch-carrot2 with Apache License 2.0 5 votes vote down vote up
static void emitErrorResponse(RestChannel channel,
                              Logger logger,
                              Exception e) {
    try {
        channel.sendResponse(new BytesRestResponse(channel, e));
    } catch (IOException e1) {
        logger.error("Failed to send failure response.", e1);
    }
}
 
Example #24
Source File: RestTermVectorsAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
    TermVectorsRequest termVectorsRequest = new TermVectorsRequest(request.param("index"), request.param("type"), request.param("id"));
    if (RestActions.hasBodyContent(request)) {
        try (XContentParser parser = XContentFactory.xContent(RestActions.guessBodyContentType(request)).createParser(RestActions.getRestContent(request))){
            TermVectorsRequest.parseRequest(termVectorsRequest, parser);
        }
    }
    readURIParameters(termVectorsRequest, request);

    client.termVectors(termVectorsRequest, new RestToXContentListener<TermVectorsResponse>(channel));
}
 
Example #25
Source File: AccountRestAction.java    From elasticsearch-auth with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleRequest(final RestRequest request,
        final RestChannel channel, final Client client) {
    final BytesReference content = request.content();
    final XContentType xContentType = XContentFactory.xContentType(content);
    XContentParser parser = null;
    String authenticator = null;
    String username = null;
    String password = null;
    String[] roles = null;
    try {
        parser = XContentFactory.xContent(xContentType).createParser(
                content);
        final XContentParser.Token t = parser.nextToken();
        if (t != null) {
            final Map<String, Object> contentMap = parser.map();
            authenticator = MapUtil.getAsString(contentMap,
                    "authenticator", null);
            username = MapUtil.getAsString(contentMap, "username", null);
            password = MapUtil.getAsString(contentMap, "password", null);
            roles = MapUtil.getAsArray(contentMap, "roles", new String[0]);
        }
    } catch (final Exception e) {
        logger.error("Could not parse the content.", e);
        ResponseUtil.send(request, channel, RestStatus.BAD_REQUEST,
                "message", "Could not parse the content.");
        return;
    } finally {
        if (parser != null) {
            parser.close();
        }
    }

    processRequest(request, channel, authenticator, username, password,
            roles);

}
 
Example #26
Source File: RestExecuteAnomalyDetectorAction.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
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 #27
Source File: RestExecuteAnomalyDetectorAction.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
private RestActionListener<GetResponse> onGetAnomalyDetectorResponse(RestChannel channel, AnomalyDetectorExecutionInput input) {
    return new RestActionListener<GetResponse>(channel) {
        @Override
        protected void processResponse(GetResponse response) throws Exception {
            if (!response.isExists()) {
                XContentBuilder message = channel
                    .newErrorBuilder()
                    .startObject()
                    .field("message", "Can't find anomaly detector with id:" + response.getId())
                    .endObject();
                channel.sendResponse(new BytesRestResponse(RestStatus.NOT_FOUND, message));
                return;
            }
            XContentParser parser = XContentType.JSON
                .xContent()
                .createParser(
                    channel.request().getXContentRegistry(),
                    LoggingDeprecationHandler.INSTANCE,
                    response.getSourceAsBytesRef().streamInput()
                );

            ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser::getTokenLocation);
            AnomalyDetector detector = AnomalyDetector.parse(parser, response.getId(), response.getVersion());

            anomalyDetectorRunner
                .executeDetector(
                    detector,
                    input.getPeriodStart(),
                    input.getPeriodEnd(),
                    getPreviewDetectorActionListener(channel, detector)
                );
        }
    };
}
 
Example #28
Source File: RestRepositoriesAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected void doRequest(final RestRequest request, RestChannel channel, Client client) {
    GetRepositoriesRequest getRepositoriesRequest = new GetRepositoriesRequest();
    getRepositoriesRequest.local(request.paramAsBoolean("local", getRepositoriesRequest.local()));
    getRepositoriesRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRepositoriesRequest.masterNodeTimeout()));

    client.admin().cluster().getRepositories(getRepositoriesRequest, new RestResponseListener<GetRepositoriesResponse>(channel) {
        @Override
        public RestResponse buildResponse(GetRepositoriesResponse getRepositoriesResponse) throws Exception {
            return RestTable.buildResponse(buildTable(request, getRepositoriesResponse), channel);
        }
    });
}
 
Example #29
Source File: IndexAnomalyDetectorActionHandler.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #30
Source File: RestStatsAnomalyDetectorAction.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
/**
 * Make the 2 requests to get the node and cluster statistics
 *
 * @param client Client
 * @param channel Channel to send response
 * @param adStatsRequest Request containing stats to be retrieved
 */
private void getStats(Client client, RestChannel channel, ADStatsRequest adStatsRequest) {
    // Use MultiResponsesDelegateActionListener to execute 2 async requests and create the response once they finish
    MultiResponsesDelegateActionListener<ADStatsResponse> delegateListener = new MultiResponsesDelegateActionListener<>(
        getRestStatsListener(channel),
        2,
        "Unable to return AD Stats"
    );

    getClusterStats(client, delegateListener, adStatsRequest);
    getNodeStats(client, delegateListener, adStatsRequest);
}