org.elasticsearch.rest.BytesRestResponse Java Examples
The following examples show how to use
org.elasticsearch.rest.BytesRestResponse.
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: AnomalyDetectorActionHandler.java From anomaly-detection with Apache License 2.0 | 6 votes |
/** * 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 #2
Source File: TasteActionRestAction.java From elasticsearch-taste with Apache License 2.0 | 6 votes |
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 #3
Source File: ReindexRestAction.java From elasticsearch-reindexing with Apache License 2.0 | 6 votes |
private void sendResponse(final RestRequest request, final RestChannel channel, final Map<String, Object> params) { try { final XContentBuilder builder = JsonXContent.contentBuilder(); if (request.hasParam("pretty")) { builder.prettyPrint().lfAtEnd(); } builder.startObject(); builder.field("acknowledged", true); 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 #4
Source File: IndexAnomalyDetectorActionHandler.java From anomaly-detection with Apache License 2.0 | 6 votes |
/** * Prepare for indexing a new anomaly detector. */ private void prepareAnomalyDetectorIndexing() { // TODO: check if aggregation query will return only one number. Not easy to validate, // 1).If index has only one document // 2).If filter will only return one document, // 3).If custom expression has specific logic to return one number for some case, // but multiple for others, like some if/else branch String error = RestHandlerUtils.validateAnomalyDetector(anomalyDetector, maxAnomalyFeatures); if (StringUtils.isNotBlank(error)) { channel.sendResponse(new BytesRestResponse(RestStatus.BAD_REQUEST, error)); return; } if (channel.request().method() == RestRequest.Method.PUT) { handler.getDetectorJob(clusterService, client, detectorId, channel, () -> updateAnomalyDetector(client, detectorId)); } else { createAnomalyDetector(); } }
Example #5
Source File: IndexAnomalyDetectorJobActionHandler.java From anomaly-detection with Apache License 2.0 | 6 votes |
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 #6
Source File: IndexAnomalyDetectorJobActionHandler.java From anomaly-detection with Apache License 2.0 | 6 votes |
private void onIndexAnomalyDetectorJobResponse(IndexResponse response, AnomalyDetectorFunction function) throws IOException { if (response == null || (response.getResult() != CREATED && response.getResult() != UPDATED)) { channel.sendResponse(new BytesRestResponse(response.status(), response.toXContent(channel.newErrorBuilder(), EMPTY_PARAMS))); return; } if (function != null) { function.execute(); } else { XContentBuilder builder = channel .newBuilder() .startObject() .field(RestHandlerUtils._ID, response.getId()) .field(RestHandlerUtils._VERSION, response.getVersion()) .field(RestHandlerUtils._SEQ_NO, response.getSeqNo()) .field(RestHandlerUtils._PRIMARY_TERM, response.getPrimaryTerm()) .endObject(); channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder)); } }
Example #7
Source File: HomeAction.java From zentity with Apache License 2.0 | 6 votes |
@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 File: CSVResultRestExecutor.java From elasticsearch-sql with Apache License 2.0 | 6 votes |
@Override public void execute(Client client, Map<String, String> params, QueryAction queryAction, RestChannel channel) throws Exception { Object queryResult = QueryActionElasticExecutor.executeAnyAction(client, queryAction); boolean flat = getBooleanOrDefault(params,"flat",false); String separator = ","; if(params.containsKey("separator")){ separator = params.get("separator"); } boolean includeScore = getBooleanOrDefault(params,"_score",false); boolean includeType = getBooleanOrDefault(params,"_type",false); boolean includeId = getBooleanOrDefault(params,"_id",false); boolean includeScrollId = getBooleanOrDefault(params,"_scroll_id",false); CSVResult result = new CSVResultsExtractor(includeScore,includeType,includeId,includeScrollId,queryAction).extractResults(queryResult,flat,separator); String newLine = "\n"; if(params.containsKey("newLine")){ newLine = params.get("newLine"); } boolean showHeader = getBooleanOrDefault(params, "showHeader", true); String csvString = buildString(separator, result, newLine, showHeader); BytesRestResponse bytesRestResponse = new BytesRestResponse(RestStatus.OK, csvString); channel.sendResponse(bytesRestResponse); }
Example #9
Source File: ResponseUtil.java From Elasticsearch with Apache License 2.0 | 6 votes |
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 #10
Source File: AnomalyDetectorActionHandler.java From anomaly-detection with Apache License 2.0 | 6 votes |
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 #11
Source File: RestUpgradeAction.java From Elasticsearch with Apache License 2.0 | 6 votes |
void handlePost(final RestRequest request, RestChannel channel, Client client) { UpgradeRequest upgradeReq = new UpgradeRequest(Strings.splitStringByCommaToArray(request.param("index"))); upgradeReq.upgradeOnlyAncientSegments(request.paramAsBoolean("only_ancient_segments", false)); client.admin().indices().upgrade(upgradeReq, new RestBuilderListener<UpgradeResponse>(channel) { @Override public RestResponse buildResponse(UpgradeResponse response, XContentBuilder builder) throws Exception { builder.startObject(); buildBroadcastShardsHeader(builder, request, response); builder.startObject("upgraded_indices"); for (Map.Entry<String, Tuple<Version, String>> entry : response.versions().entrySet()) { builder.startObject(entry.getKey(), XContentBuilder.FieldCaseConversion.NONE); builder.field("upgrade_version", entry.getValue().v1()); builder.field("oldest_lucene_segment_version", entry.getValue().v2()); builder.endObject(); } builder.endObject(); builder.endObject(); return new BytesRestResponse(OK, builder); } }); }
Example #12
Source File: RestDataAction.java From elasticsearch-dataformat with Apache License 2.0 | 6 votes |
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 #13
Source File: RestDeleteAnomalyDetectorAction.java From anomaly-detection with Apache License 2.0 | 6 votes |
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 #14
Source File: RestFeatureStoreCaches.java From elasticsearch-learning-to-rank with Apache License 2.0 | 6 votes |
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 #15
Source File: ResponseUtil.java From elasticsearch-auth with Apache License 2.0 | 6 votes |
public static void send(final RestRequest request, final RestChannel channel, final RestStatus status, final String... args) { try { final XContentBuilder builder = JsonXContent.contentBuilder(); builder.startObject(); builder.field("status", status.getStatus()); for (int i = 0; i < args.length; i += 2) { builder.field(args[i], args[i + 1]); } builder.endObject(); channel.sendResponse(new BytesRestResponse(status, builder)); } 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 #16
Source File: HTTPSamlAuthenticator.java From deprecated-security-advanced-modules with Apache License 2.0 | 6 votes |
@Override public boolean reRequestAuthentication(RestChannel restChannel, AuthCredentials authCredentials) { try { RestRequest restRequest = restChannel.request(); if ("/_opendistro/_security/api/authtoken".equals(restRequest.path()) && this.authTokenProcessorHandler.handle(restRequest, restChannel)) { return true; } Saml2Settings saml2Settings = this.saml2SettingsProvider.getCached(); BytesRestResponse authenticateResponse = new BytesRestResponse(RestStatus.UNAUTHORIZED, ""); authenticateResponse.addHeader("WWW-Authenticate", getWwwAuthenticateHeader(saml2Settings)); restChannel.sendResponse(authenticateResponse); return true; } catch (Exception e) { log.error("Error in reRequestAuthentication()", e); return false; } }
Example #17
Source File: RestDataAction.java From elasticsearch-dataformat with Apache License 2.0 | 5 votes |
@Override public void onFailure(final Exception e) { deleteOutputFile(); try { channel.sendResponse(new BytesRestResponse(channel, RestStatus.INTERNAL_SERVER_ERROR, e)); } catch (final IOException e1) { logger.error("Failed to send failure response", e1); } }
Example #18
Source File: S3ManageAction.java From es-amazon-s3-river with Apache License 2.0 | 5 votes |
/** */ private void onFailure(RestRequest request, RestChannel channel, Exception e) throws Exception{ try{ channel.sendResponse(new BytesRestResponse(channel, e)); } catch (IOException ioe){ logger.error("Sending failure response fails !", e); channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR)); } }
Example #19
Source File: CommandRestHandler.java From elasticsearch-rest-command with The Unlicense | 5 votes |
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: RestDataAction.java From elasticsearch-dataformat with Apache License 2.0 | 5 votes |
private void writeResponse(final RestRequest request, final RestChannel channel, final File outputFile, final long limit, final DataContent dataContent) { if (outputFile.length() > limit) { onFailure(new ElasticsearchException("Content size is too large " + outputFile.length())); return; } try (FileInputStream fis = new FileInputStream(outputFile)) { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final byte[] bytes = new byte[1024]; int len; while ((len = fis.read(bytes)) > 0) { out.write(bytes, 0, len); } final ContentType contentType = dataContent.getContentType(); final BytesRestResponse response = new BytesRestResponse( RestStatus.OK, contentType.contentType(), out.toByteArray()); response.addHeader("Content-Disposition", "attachment; filename=\"" + contentType.fileName(request) + "\""); channel.sendResponse(response); } catch (final Throwable e) { throw new ElasticsearchException("Failed to render the content.", e); } }
Example #21
Source File: JobRestHandler.java From elasticsearch-rest-command with The Unlicense | 5 votes |
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 #22
Source File: S3ManageAction.java From es-amazon-s3-river with Apache License 2.0 | 5 votes |
@Override public void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception{ if (logger.isDebugEnabled()){ logger.debug("REST S3ManageAction called"); } String rivername = request.param("rivername"); String command = request.param("command"); String status = null; if (START_COMMAND.equals(command)){ status = "STARTED"; } else if (STOP_COMMAND.equals(command)){ status = "STOPPED"; } try{ if (status != null){ XContentBuilder xb = jsonBuilder() .startObject() .startObject("amazon-s3") .field("feedname", rivername) .field("status", status) .endObject() .endObject(); client.prepareIndex("_river", rivername, "_s3status").setSource(xb).execute().actionGet(); } XContentBuilder builder = jsonBuilder(); builder .startObject() .field(new XContentBuilderString("ok"), true) .endObject(); channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder)); } catch (IOException e) { onFailure(request, channel, e); } }
Example #23
Source File: AcknowledgedRestListener.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public RestResponse buildResponse(T response, XContentBuilder builder) throws Exception { builder.startObject() .field(Fields.ACKNOWLEDGED, response.isAcknowledged()); addCustomFields(builder, response); builder.endObject(); return new BytesRestResponse(OK, builder); }
Example #24
Source File: ReindexRestAction.java From elasticsearch-reindexing with Apache License 2.0 | 5 votes |
private void sendErrorResponse(final RestChannel channel, final Throwable t) { try { channel.sendResponse(new BytesRestResponse(channel, t)); } catch (final Exception e) { logger.error( "Failed to send a failure response: " + t.getMessage(), e); } }
Example #25
Source File: GetIndexRequestRestListener.java From elasticsearch-sql with Apache License 2.0 | 5 votes |
@Override public RestResponse buildResponse(GetIndexResponse getIndexResponse, XContentBuilder builder) throws Exception { GetIndexRequest.Feature[] features = getIndexRequest.features(); String[] indices = getIndexResponse.indices(); builder.startObject(); for (String index : indices) { builder.startObject(index); for (GetIndexRequest.Feature feature : features) { switch (feature) { case ALIASES: writeAliases(getIndexResponse.aliases().get(index), builder, channel.request()); break; case MAPPINGS: writeMappings(getIndexResponse.mappings().get(index), builder, channel.request()); break; case SETTINGS: writeSettings(getIndexResponse.settings().get(index), builder, channel.request()); break; default: throw new IllegalStateException("feature [" + feature + "] is not valid"); } } builder.endObject(); } builder.endObject(); return new BytesRestResponse(RestStatus.OK, builder); }
Example #26
Source File: ElasticDefaultRestExecutor.java From elasticsearch-sql with Apache License 2.0 | 5 votes |
private void sendDefaultResponse(SearchHits hits, RestChannel channel) { try { XContentBuilder builder = ElasticUtils.hitsAsXContentBuilder(hits, new MetaSearchResult()); BytesRestResponse bytesRestResponse = new BytesRestResponse(RestStatus.OK, builder); channel.sendResponse(bytesRestResponse); } catch (IOException e) { e.printStackTrace(); } }
Example #27
Source File: ElasticJoinExecutor.java From elasticsearch-sql with Apache License 2.0 | 5 votes |
public void sendResponse(RestChannel channel){ try { XContentBuilder builder = ElasticUtils.hitsAsXContentBuilder(results,metaResults); BytesRestResponse bytesRestResponse = new BytesRestResponse(RestStatus.OK, builder); channel.sendResponse(bytesRestResponse); } catch (IOException e) { e.printStackTrace(); } }
Example #28
Source File: XmlFilter.java From elasticsearch-xml with Apache License 2.0 | 5 votes |
@Override public void sendResponse(RestResponse response) { if (!response.status().equals(RestStatus.OK)) { channel.sendResponse(response); } if (isXml(request)) { XContentParser parser = null; try { String string = response.content().toUtf8(); // takes some space ... :( XContentType xContentType = XContentFactory.xContentType(string); parser = XContentFactory.xContent(xContentType).createParser(string); parser.nextToken(); XmlXContentBuilder builder = XmlXContentFactory.xmlBuilder(params); if (request.paramAsBoolean("pretty", false)) { builder.prettyPrint(); } builder.copyCurrentStructure(parser); BytesRestResponse restResponse = new BytesRestResponse(RestStatus.OK, "text/xml; charset=UTF-8", builder.bytes()); channel.sendResponse(restResponse); return; } catch (Throwable e) { logger.error(e.getMessage(), e); channel.sendResponse(new BytesRestResponse(RestStatus.INTERNAL_SERVER_ERROR, e.getMessage())); return; } finally { if (parser != null) { parser.close(); } } } channel.sendResponse(response); }
Example #29
Source File: RestSimpleFeatureStore.java From elasticsearch-learning-to-rank with Apache License 2.0 | 5 votes |
RestChannelConsumer getStore(NodeClient client, String indexName) { return (channel) -> client.admin().indices().prepareExists(indexName) .execute(new RestBuilderListener<IndicesExistsResponse>(channel) { @Override public RestResponse buildResponse(IndicesExistsResponse indicesExistsResponse, XContentBuilder builder) throws Exception { builder.startObject() .field("exists", indicesExistsResponse.isExists()) .endObject() .close(); return new BytesRestResponse(indicesExistsResponse.isExists() ? RestStatus.OK : RestStatus.NOT_FOUND, builder); } }); }
Example #30
Source File: HTTPJwtAuthenticator.java From deprecated-security-advanced-modules with Apache License 2.0 | 5 votes |
@Override public boolean reRequestAuthentication(final RestChannel channel, AuthCredentials creds) { final BytesRestResponse wwwAuthenticateResponse = new BytesRestResponse(RestStatus.UNAUTHORIZED,""); wwwAuthenticateResponse.addHeader("WWW-Authenticate", "Bearer realm=\"Open Distro Security\""); channel.sendResponse(wwwAuthenticateResponse); return true; }