Java Code Examples for org.elasticsearch.rest.RestChannel#sendResponse()

The following examples show how to use org.elasticsearch.rest.RestChannel#sendResponse() . 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: 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 3
Source File: ResponseUtil.java    From elasticsearch-auth with Apache License 2.0 6 votes vote down vote up
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 4
Source File: ReindexRestAction.java    From elasticsearch-reindexing 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) {
    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 5
Source File: CSVResultRestExecutor.java    From elasticsearch-sql with Apache License 2.0 6 votes vote down vote up
@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 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: 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 8
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 9
Source File: JobRestHandler.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
private void sendTimeline(final RestRequest request,final RestChannel channel, SearchResponse response){
	XContentBuilder builder;
	try {
		builder = channel.newBuilder();							
		Search.buildTimeline(builder, response, logger);	
		channel.sendResponse(new BytesRestResponse(response.status(), builder));
	} catch (IOException e) {
		sendFailure(request, channel, e);
	}
}
 
Example 10
Source File: S3ManageAction.java    From es-amazon-s3-river with Apache License 2.0 5 votes vote down vote up
/** */
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 11
Source File: ElasticDefaultRestExecutor.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
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 12
Source File: S3ManageAction.java    From es-amazon-s3-river with Apache License 2.0 5 votes vote down vote up
@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 13
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 14
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 15
Source File: AbstractApiAction.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
protected void response(RestChannel channel, RestStatus status, String message) {

		try {
			final XContentBuilder builder = channel.newBuilder();
			builder.startObject();
			builder.field("status", status.name());
			builder.field("message", message);
			builder.endObject();
			channel.sendResponse(new BytesRestResponse(status, builder));
		} catch (IOException e) {
			throw ExceptionsHelper.convertToElastic(e);
		}
	}
 
Example 16
Source File: JobRestHandler.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
private void sendQuery(int from, final RestRequest request,final RestChannel channel, SearchResponse response, List<String> fieldNames, boolean showMeta){
	XContentBuilder builder;
	try {
		builder = channel.newBuilder();								
		Search.buildQuery(from, builder, response, logger, fieldNames, showMeta);								
		channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
	} catch (IOException e) {
		sendFailure(request, channel, e);
	}
}
 
Example 17
Source File: HTTPJwtAuthenticator.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 18
Source File: KafkaStreamRestHandler.java    From elasticsearch-rest-command with The Unlicense 4 votes vote down vote up
@Override
protected void handleRequest(RestRequest request, RestChannel channel, Client client)
		throws Exception {
	final String topic = request.param("topic", "");
	final boolean schema = request.paramAsBoolean("schema", false);
	final String master = request.param("masterAddress", "local");
	final String hdfs =  request.param("hdfs", "hdfs://localhost:50070");
	final String memory =  request.param("memory", "2g");
	final String appName = request.param("appName", "appName-"+topic);
	final int duration = request.paramAsInt("duration", 1000);
	
	Thread exec = new Thread(new Runnable(){

		@Override
		public void run() {
		
			SparkConf sparkConf = new SparkConf().setAppName(appName).setMaster(master).set("spark.executor.memory", memory);
			JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, new Duration(duration));
			
			Map<String, Integer> topicMap = new HashMap<String, Integer>();
			topicMap.put(topic, 3);
			
			JavaPairReceiverInputDStream<String, byte[]> kafkaStream = KafkaUtils.createStream(jssc, String.class, byte[].class, 
						kafka.serializer.DefaultDecoder.class, kafka.serializer.DefaultDecoder.class, null, 
						topicMap,  StorageLevel.MEMORY_ONLY());
	
			//JobConf confHadoop = new JobConf();
			//confHadoop.set("mapred.output.compress", "true");
			//confHadoop.set("mapred.output.compression.codec", "com.hadoop.compression.lzo.LzopCodec");
	
			kafkaStream.saveAsHadoopFiles(hdfs, "seq", Text.class, BytesWritable.class, KafkaStreamSeqOutputFormat.class);
			
			topicContextMap.put(topic, jssc);
			jssc.start();		
			jssc.awaitTermination();
			
		}
	});
	
	exec.start();
	
	channel.sendResponse(new BytesRestResponse(RestStatus.OK, String.format("{\"topic\":\"%s\"}",  topic)));
	
	
}
 
Example 19
Source File: AbstractApiAction.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
protected void badRequestResponse(RestChannel channel, AbstractConfigurationValidator validator) {
	channel.sendResponse(new BytesRestResponse(RestStatus.BAD_REQUEST, validator.errorsAsXContent(channel)));
}
 
Example 20
Source File: AbstractApiAction.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
protected void successResponse(RestChannel channel, SecurityDynamicConfiguration<?> response) {
	channel.sendResponse(
			new BytesRestResponse(RestStatus.OK, convertToJson(channel, response)));
}