Exemple #1
0
 private static String renderValue(RestRequest request, Object value) {
   if (value == null) {
     return null;
   }
   if (value instanceof ByteSizeValue) {
     ByteSizeValue v = (ByteSizeValue) value;
     String resolution = request.param("bytes");
     if ("b".equals(resolution)) {
       return Long.toString(v.bytes());
     } else if ("k".equals(resolution)) {
       return Long.toString(v.kb());
     } else if ("m".equals(resolution)) {
       return Long.toString(v.mb());
     } else if ("g".equals(resolution)) {
       return Long.toString(v.gb());
     } else if ("t".equals(resolution)) {
       return Long.toString(v.tb());
     } else if ("p".equals(resolution)) {
       return Long.toString(v.pb());
     } else {
       return v.toString();
     }
   }
   if (value instanceof SizeValue) {
     SizeValue v = (SizeValue) value;
     String resolution = request.param("size");
     if ("b".equals(resolution)) {
       return Long.toString(v.singles());
     } else if ("k".equals(resolution)) {
       return Long.toString(v.kilo());
     } else if ("m".equals(resolution)) {
       return Long.toString(v.mega());
     } else if ("g".equals(resolution)) {
       return Long.toString(v.giga());
     } else if ("t".equals(resolution)) {
       return Long.toString(v.tera());
     } else if ("p".equals(resolution)) {
       return Long.toString(v.peta());
     } else {
       return v.toString();
     }
   }
   if (value instanceof TimeValue) {
     TimeValue v = (TimeValue) value;
     String resolution = request.param("time");
     if ("ms".equals(resolution)) {
       return Long.toString(v.millis());
     } else if ("s".equals(resolution)) {
       return Long.toString(v.seconds());
     } else if ("m".equals(resolution)) {
       return Long.toString(v.minutes());
     } else if ("h".equals(resolution)) {
       return Long.toString(v.hours());
     } else {
       return v.toString();
     }
   }
   // Add additional built in data points we can render based on request parameters?
   return value.toString();
 }
 public static byte[] parseQuerySource(RestRequest request) {
   if (request.hasContent()) {
     return request.contentAsBytes();
   }
   String queryString = request.param("q");
   if (queryString == null) {
     throw new ElasticSearchIllegalArgumentException(
         "No query to execute, not in body, and not bounded to 'q' parameter");
   }
   QueryStringJsonQueryBuilder queryBuilder = JsonQueryBuilders.queryString(queryString);
   queryBuilder.defaultField(request.param("df"));
   queryBuilder.analyzer(request.param("analyzer"));
   String defaultOperator = request.param("default_operator");
   if (defaultOperator != null) {
     if ("OR".equals(defaultOperator)) {
       queryBuilder.defaultOperator(QueryStringJsonQueryBuilder.Operator.OR);
     } else if ("AND".equals(defaultOperator)) {
       queryBuilder.defaultOperator(QueryStringJsonQueryBuilder.Operator.AND);
     } else {
       throw new ElasticSearchIllegalArgumentException(
           "Unsupported defaultOperator [" + defaultOperator + "], can either be [OR] or [AND]");
     }
   }
   return queryBuilder.buildAsBytes();
 }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    MultiSearchRequest multiSearchRequest = new MultiSearchRequest();
    multiSearchRequest.listenerThreaded(false);

    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    String[] types = Strings.splitStringByCommaToArray(request.param("type"));
    IndicesOptions indicesOptions =
        IndicesOptions.fromRequest(request, multiSearchRequest.indicesOptions());

    try {
      multiSearchRequest.add(
          request.content(),
          request.contentUnsafe(),
          indices,
          types,
          request.param("search_type"),
          request.param("routing"),
          indicesOptions,
          allowExplicitIndex);
    } catch (Exception e) {
      try {
        XContentBuilder builder = restContentBuilder(request);
        channel.sendResponse(
            new XContentRestResponse(
                request,
                BAD_REQUEST,
                builder.startObject().field("error", e.getMessage()).endObject()));
      } catch (IOException e1) {
        logger.error("Failed to send failure response", e1);
      }
      return;
    }

    client.multiSearch(
        multiSearchRequest,
        new ActionListener<MultiSearchResponse>() {
          @Override
          public void onResponse(MultiSearchResponse response) {
            try {
              XContentBuilder builder = restContentBuilder(request);
              builder.startObject();
              response.toXContent(builder, request);
              builder.endObject();
              channel.sendResponse(new XContentRestResponse(request, OK, builder));
            } catch (Throwable e) {
              onFailure(e);
            }
          }

          @Override
          public void onFailure(Throwable e) {
            try {
              channel.sendResponse(new XContentThrowableRestResponse(request, e));
            } catch (IOException e1) {
              logger.error("Failed to send failure response", e1);
            }
          }
        });
  }
 @Override
 public void handleRequest(final RestRequest request, final RestChannel channel, Client client) {
   DeleteIndexedScriptRequest deleteIndexedScriptRequest =
       new DeleteIndexedScriptRequest(getScriptLang(request), request.param("id"));
   deleteIndexedScriptRequest.version(
       request.paramAsLong("version", deleteIndexedScriptRequest.version()));
   deleteIndexedScriptRequest.versionType(
       VersionType.fromString(
           request.param("version_type"), deleteIndexedScriptRequest.versionType()));
   client.deleteIndexedScript(
       deleteIndexedScriptRequest,
       new RestBuilderListener<DeleteIndexedScriptResponse>(channel) {
         @Override
         public RestResponse buildResponse(
             DeleteIndexedScriptResponse result, XContentBuilder builder) throws Exception {
           builder
               .startObject()
               .field(Fields.FOUND, result.isFound())
               .field(Fields._INDEX, result.getIndex())
               .field(Fields._TYPE, result.getType())
               .field(Fields._ID, result.getId())
               .field(Fields._VERSION, result.getVersion())
               .endObject();
           RestStatus status = OK;
           if (!result.isFound()) {
             status = NOT_FOUND;
           }
           return new BytesRestResponse(status, builder);
         }
       });
 }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    DeleteMappingRequest deleteMappingRequest =
        deleteMappingRequest(splitIndices(request.param("index")));
    deleteMappingRequest.type(request.param("type"));
    client
        .admin()
        .indices()
        .deleteMapping(
            deleteMappingRequest,
            new ActionListener<DeleteMappingResponse>() {
              @Override
              public void onResponse(DeleteMappingResponse response) {
                try {
                  XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
                  builder.startObject().field("ok", true);
                  builder.endObject();
                  channel.sendResponse(new XContentRestResponse(request, OK, builder));
                } catch (IOException e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new XContentThrowableRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
  private RestChannelConsumer parseExistingDocPercolate(
      PercolateRequest percolateRequest, RestRequest restRequest, NodeClient client) {
    String index = restRequest.param("index");
    String type = restRequest.param("type");
    percolateRequest.indices(
        Strings.splitStringByCommaToArray(restRequest.param("percolate_index", index)));
    percolateRequest.documentType(restRequest.param("percolate_type", type));

    GetRequest getRequest = new GetRequest(index, type, restRequest.param("id"));
    getRequest.routing(restRequest.param("routing"));
    getRequest.preference(restRequest.param("preference"));
    getRequest.refresh(restRequest.paramAsBoolean("refresh", getRequest.refresh()));
    getRequest.realtime(restRequest.paramAsBoolean("realtime", getRequest.realtime()));
    getRequest.version(RestActions.parseVersion(restRequest));
    getRequest.versionType(
        VersionType.fromString(restRequest.param("version_type"), getRequest.versionType()));

    percolateRequest.getRequest(getRequest);
    percolateRequest.routing(restRequest.param("percolate_routing"));
    percolateRequest.preference(restRequest.param("percolate_preference"));
    percolateRequest.source(restRequest.contentOrSourceParam());

    percolateRequest.indicesOptions(
        IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    return channel -> executePercolate(client, percolateRequest, channel);
  }
 protected AbstractRestChannel(RestRequest request, boolean detailedErrorsEnabled) {
   this.request = request;
   this.detailedErrorsEnabled = detailedErrorsEnabled;
   this.format = request.param("format", request.header("Accept"));
   this.filterPath = request.param("filter_path", null);
   this.pretty = request.paramAsBoolean("pretty", false);
   this.human = request.paramAsBoolean("human", false);
 }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    String text = request.param("text");
    if (text == null && request.hasContent()) {
      text = request.content().toUtf8();
    }
    if (text == null) {
      try {
        channel.sendResponse(
            new XContentThrowableRestResponse(
                request, new ElasticsearchIllegalArgumentException("text is missing")));
      } catch (IOException e1) {
        logger.warn("Failed to send response", e1);
      }
      return;
    }

    AnalyzeRequest analyzeRequest = new AnalyzeRequest(request.param("index"), text);
    analyzeRequest.listenerThreaded(false);
    analyzeRequest.preferLocal(
        request.paramAsBoolean("prefer_local", analyzeRequest.preferLocalShard()));
    analyzeRequest.analyzer(request.param("analyzer"));
    analyzeRequest.field(request.param("field"));
    analyzeRequest.tokenizer(request.param("tokenizer"));
    analyzeRequest.tokenFilters(
        request.paramAsStringArray(
            "token_filters", request.paramAsStringArray("filters", analyzeRequest.tokenFilters())));
    analyzeRequest.charFilters(
        request.paramAsStringArray("char_filters", analyzeRequest.charFilters()));
    client
        .admin()
        .indices()
        .analyze(
            analyzeRequest,
            new ActionListener<AnalyzeResponse>() {
              @Override
              public void onResponse(AnalyzeResponse response) {
                try {
                  XContentBuilder builder = restContentBuilder(request, null);
                  builder.startObject();
                  response.toXContent(builder, request);
                  builder.endObject();
                  channel.sendResponse(new XContentRestResponse(request, OK, builder));
                } catch (Throwable e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new XContentThrowableRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
  @SuppressWarnings({"unchecked"})
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    PutIndexTemplateRequest putRequest = new PutIndexTemplateRequest(request.param("name"));

    try {
      putRequest.create(request.paramAsBoolean("create", false));
      putRequest.cause(request.param("cause", ""));
      putRequest.timeout(request.paramAsTime("timeout", timeValueSeconds(10)));
      putRequest.source(
          request.contentByteArray(), request.contentByteArrayOffset(), request.contentLength());
    } catch (Exception e) {
      try {
        channel.sendResponse(new XContentThrowableRestResponse(request, e));
      } catch (IOException e1) {
        logger.warn("Failed to send response", e1);
      }
      return;
    }

    putRequest.template(request.param("template", putRequest.template()));
    putRequest.order(request.paramAsInt("order", putRequest.order()));

    client
        .admin()
        .indices()
        .putTemplate(
            putRequest,
            new ActionListener<PutIndexTemplateResponse>() {
              @Override
              public void onResponse(PutIndexTemplateResponse response) {
                try {
                  XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
                  builder
                      .startObject()
                      .field(Fields.OK, true)
                      .field(Fields.ACKNOWLEDGED, response.acknowledged())
                      .endObject();
                  channel.sendResponse(new XContentRestResponse(request, OK, builder));
                } catch (IOException e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new XContentThrowableRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
  private RestChannelConsumer parseDocPercolate(
      PercolateRequest percolateRequest, RestRequest restRequest, NodeClient client) {
    percolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("index")));
    percolateRequest.documentType(restRequest.param("type"));
    percolateRequest.routing(restRequest.param("routing"));
    percolateRequest.preference(restRequest.param("preference"));
    percolateRequest.source(restRequest.contentOrSourceParam());

    percolateRequest.indicesOptions(
        IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    return channel -> executePercolate(client, percolateRequest, channel);
  }
  public JsonContent(
      final Client client,
      final RestRequest request,
      final RestChannel channel,
      final SearchType searchType) {
    super(client, request, searchType);

    nettyChannel = NettyUtils.getChannel(channel);

    bulkIndex = request.param("bulk.index");
    bulkType = request.param("bulk.type");
  }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final Client client)
     throws IOException {
   final SearchRequest searchRequest =
       new SearchRequest(
           Strings.splitStringByCommaToArray(request.param("index")), new SearchSourceBuilder());
   searchRequest.indicesOptions(
       IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));
   if (RestActions.hasBodyContent(request)) {
     final BytesReference sourceBytes = RestActions.getRestContent(request);
     try (XContentParser parser =
         XContentFactory.xContent(sourceBytes).createParser(sourceBytes)) {
       final QueryParseContext context =
           new QueryParseContext(queryRegistry, parser, parseFieldMatcher);
       searchRequest.source().suggest(SuggestBuilder.fromXContent(context, suggesters));
     }
   } else {
     throw new IllegalArgumentException("no content or source provided to execute suggestion");
   }
   searchRequest.routing(request.param("routing"));
   searchRequest.preference(request.param("preference"));
   client.search(
       searchRequest,
       new RestBuilderListener<SearchResponse>(channel) {
         @Override
         public RestResponse buildResponse(SearchResponse response, XContentBuilder builder)
             throws Exception {
           RestStatus restStatus =
               RestStatus.status(
                   response.getSuccessfulShards(),
                   response.getTotalShards(),
                   response.getShardFailures());
           builder.startObject();
           buildBroadcastShardsHeader(
               builder,
               request,
               response.getTotalShards(),
               response.getSuccessfulShards(),
               response.getFailedShards(),
               response.getShardFailures());
           Suggest suggest = response.getSuggest();
           if (suggest != null) {
             suggest.toInnerXContent(builder, request);
           }
           builder.endObject();
           return new BytesRestResponse(restStatus, builder);
         }
       });
 }
  void parseDocPercolate(
      PercolateRequest percolateRequest,
      RestRequest restRequest,
      RestChannel restChannel,
      final Client client) {
    percolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("index")));
    percolateRequest.documentType(restRequest.param("type"));
    percolateRequest.routing(restRequest.param("routing"));
    percolateRequest.preference(restRequest.param("preference"));
    percolateRequest.source(RestActions.getRestContent(restRequest));

    percolateRequest.indicesOptions(
        IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    executePercolate(percolateRequest, restChannel, client);
  }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final NodeClient client) {
   RestoreSnapshotRequest restoreSnapshotRequest =
       restoreSnapshotRequest(request.param("repository"), request.param("snapshot"));
   restoreSnapshotRequest.masterNodeTimeout(
       request.paramAsTime("master_timeout", restoreSnapshotRequest.masterNodeTimeout()));
   restoreSnapshotRequest.waitForCompletion(request.paramAsBoolean("wait_for_completion", false));
   restoreSnapshotRequest.source(request.content().utf8ToString());
   client
       .admin()
       .cluster()
       .restoreSnapshot(
           restoreSnapshotRequest, new RestToXContentListener<RestoreSnapshotResponse>(channel));
 }
  @Override
  public void login(final RestRequest request, final ActionListener<String[]> listener) {
    String username = request.param(usernameKey);
    String password = request.param(passwordKey);
    final BytesReference content = request.content();
    final XContentType xContentType = XContentFactory.xContentType(content);
    XContentParser parser = null;
    try {
      parser = XContentFactory.xContent(xContentType).createParser(content);
      final XContentParser.Token t = parser.nextToken();
      if (t != null) {
        final Map<String, Object> contentMap = parser.map();
        username = MapUtil.getAsString(contentMap, usernameKey, username);
        password = MapUtil.getAsString(contentMap, passwordKey, password);
      }
    } catch (final Exception e) {
      listener.onFailure(e);
      return;
    } finally {
      if (parser != null) {
        parser.close();
      }
    }

    if (username == null) {
      listener.onResponse(new String[0]);
      return;
    }

    processLogin(username, password, listener);
  }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final NodeClient client) {
   GetIndexTemplatesRequest getIndexTemplatesRequest =
       new GetIndexTemplatesRequest(request.param("name"));
   getIndexTemplatesRequest.local(
       request.paramAsBoolean("local", getIndexTemplatesRequest.local()));
   getIndexTemplatesRequest.masterNodeTimeout(
       request.paramAsTime("master_timeout", getIndexTemplatesRequest.masterNodeTimeout()));
   client
       .admin()
       .indices()
       .getTemplates(
           getIndexTemplatesRequest,
           new RestResponseListener<GetIndexTemplatesResponse>(channel) {
             @Override
             public RestResponse buildResponse(
                 GetIndexTemplatesResponse getIndexTemplatesResponse) {
               boolean templateExists = getIndexTemplatesResponse.getIndexTemplates().size() > 0;
               if (templateExists) {
                 return new BytesRestResponse(
                     OK, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY);
               } else {
                 return new BytesRestResponse(
                     NOT_FOUND, BytesRestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY);
               }
             }
           });
 }
  @Override
  public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client)
      throws IOException {
    final String[] names = Strings.splitStringByCommaToArray(request.param("name"));

    GetIndexTemplatesRequest getIndexTemplatesRequest = new GetIndexTemplatesRequest(names);
    getIndexTemplatesRequest.local(
        request.paramAsBoolean("local", getIndexTemplatesRequest.local()));
    getIndexTemplatesRequest.masterNodeTimeout(
        request.paramAsTime("master_timeout", getIndexTemplatesRequest.masterNodeTimeout()));

    final boolean implicitAll = getIndexTemplatesRequest.names().length == 0;

    return channel ->
        client
            .admin()
            .indices()
            .getTemplates(
                getIndexTemplatesRequest,
                new RestToXContentListener<GetIndexTemplatesResponse>(channel) {
                  @Override
                  protected RestStatus getStatus(GetIndexTemplatesResponse response) {
                    boolean templateExists = false == response.getIndexTemplates().isEmpty();

                    return (templateExists || implicitAll) ? OK : NOT_FOUND;
                  }
                });
  }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final NodeClient client) {
   ForceMergeRequest mergeRequest =
       new ForceMergeRequest(Strings.splitStringByCommaToArray(request.param("index")));
   mergeRequest.indicesOptions(IndicesOptions.fromRequest(request, mergeRequest.indicesOptions()));
   mergeRequest.maxNumSegments(
       request.paramAsInt("max_num_segments", mergeRequest.maxNumSegments()));
   mergeRequest.onlyExpungeDeletes(
       request.paramAsBoolean("only_expunge_deletes", mergeRequest.onlyExpungeDeletes()));
   mergeRequest.flush(request.paramAsBoolean("flush", mergeRequest.flush()));
   client
       .admin()
       .indices()
       .forceMerge(
           mergeRequest,
           new RestBuilderListener<ForceMergeResponse>(channel) {
             @Override
             public RestResponse buildResponse(
                 ForceMergeResponse response, XContentBuilder builder) throws Exception {
               builder.startObject();
               buildBroadcastShardsHeader(builder, request, response);
               builder.endObject();
               return new BytesRestResponse(OK, builder);
             }
           });
 }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    IndicesExistsRequest indicesExistsRequest =
        new IndicesExistsRequest(splitIndices(request.param("index")));
    indicesExistsRequest.listenerThreaded(false);
    client
        .admin()
        .indices()
        .exists(
            indicesExistsRequest,
            new ActionListener<IndicesExistsResponse>() {
              @Override
              public void onResponse(IndicesExistsResponse response) {
                try {
                  if (response.isExists()) {
                    channel.sendResponse(new StringRestResponse(OK));
                  } else {
                    channel.sendResponse(new StringRestResponse(NOT_FOUND));
                  }
                } catch (Throwable e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new StringRestResponse(ExceptionsHelper.status(e)));
                } catch (Exception e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
  /**
   * Extracts all the required fields from the RestRequest 'h' parameter. In order to support
   * wildcards like 'bulk.*' this needs potentially parse all the configured headers and its aliases
   * and needs to ensure that everything is only added once to the returned headers, even if
   * 'h=bulk.*.bulk.*' is specified or some headers are contained twice due to matching aliases
   */
  private static Set<String> expandHeadersFromRequest(Table table, RestRequest request) {
    Set<String> headers = new LinkedHashSet<>(table.getHeaders().size());

    // check headers and aliases
    for (String header : Strings.splitStringByCommaToArray(request.param("h"))) {
      if (Regex.isSimpleMatchPattern(header)) {
        for (Table.Cell tableHeaderCell : table.getHeaders()) {
          String configuredHeader = tableHeaderCell.value.toString();
          if (Regex.simpleMatch(header, configuredHeader)) {
            headers.add(configuredHeader);
          } else if (tableHeaderCell.attr.containsKey("alias")) {
            String[] aliases = Strings.splitStringByCommaToArray(tableHeaderCell.attr.get("alias"));
            for (String alias : aliases) {
              if (Regex.simpleMatch(header, alias)) {
                headers.add(configuredHeader);
                break;
              }
            }
          }
        }
      } else {
        headers.add(header);
      }
    }

    return headers;
  }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    FlushRequest flushRequest = new FlushRequest(RestActions.splitIndices(request.param("index")));
    // we just send back a response, no need to fork a listener
    flushRequest.listenerThreaded(false);
    BroadcastOperationThreading operationThreading =
        BroadcastOperationThreading.fromString(
            request.param("operationThreading"), BroadcastOperationThreading.SINGLE_THREAD);
    if (operationThreading == BroadcastOperationThreading.NO_THREADS) {
      // since we don't spawn, don't allow no_threads, but change it to a single thread
      operationThreading = BroadcastOperationThreading.THREAD_PER_SHARD;
    }
    flushRequest.operationThreading(operationThreading);
    flushRequest.refresh(request.paramAsBoolean("refresh", flushRequest.refresh()));
    flushRequest.full(request.paramAsBoolean("full", flushRequest.full()));
    client
        .admin()
        .indices()
        .flush(
            flushRequest,
            new ActionListener<FlushResponse>() {
              @Override
              public void onResponse(FlushResponse response) {
                try {
                  XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
                  builder.startObject();
                  builder.field("ok", true);

                  buildBroadcastShardsHeader(builder, response);

                  builder.endObject();
                  channel.sendResponse(new XContentRestResponse(request, OK, builder));
                } catch (Exception e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new XContentThrowableRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, NodeClient client) {
   PutStoredScriptRequest putRequest =
       new PutStoredScriptRequest(getScriptLang(request), request.param("id"));
   putRequest.script(request.content());
   client.admin().cluster().putStoredScript(putRequest, new AcknowledgedRestListener<>(channel));
 }
 public static RestResponse buildResponse(Table table, RestRequest request, RestChannel channel)
     throws Exception {
   XContentType xContentType =
       XContentType.fromRestContentType(request.param("format", request.header("Content-Type")));
   if (xContentType != null) {
     return buildXContentBuilder(table, request, channel);
   }
   return buildTextPlainResponse(table, request, channel);
 }
 public static RestResponse buildResponse(Table table, RestChannel channel) throws Exception {
   RestRequest request = channel.request();
   XContentType xContentType =
       XContentType.fromMediaTypeOrFormat(request.param("format", request.header("Accept")));
   if (xContentType != null) {
     return buildXContentBuilder(table, channel);
   }
   return buildTextPlainResponse(table, channel);
 }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    final ClusterSearchShardsRequest clusterSearchShardsRequest =
        Requests.clusterSearchShardsRequest(indices);
    clusterSearchShardsRequest.local(
        request.paramAsBoolean("local", clusterSearchShardsRequest.local()));
    clusterSearchShardsRequest.listenerThreaded(false);

    clusterSearchShardsRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    clusterSearchShardsRequest.routing(request.param("routing"));
    clusterSearchShardsRequest.preference(request.param("preference"));
    clusterSearchShardsRequest.indicesOptions(
        IndicesOptions.fromRequest(request, clusterSearchShardsRequest.indicesOptions()));

    client
        .admin()
        .cluster()
        .searchShards(
            clusterSearchShardsRequest,
            new ActionListener<ClusterSearchShardsResponse>() {
              @Override
              public void onResponse(ClusterSearchShardsResponse response) {
                try {
                  XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
                  builder.startObject();
                  response.toXContent(builder, request);
                  builder.endObject();
                  channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
                } catch (Throwable e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new BytesRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    BroadcastPingRequest broadcastPingRequest =
        new BroadcastPingRequest(RestActions.splitIndices(request.param("index")));
    broadcastPingRequest.queryHint(request.param("query_hint"));
    BroadcastOperationThreading operationThreading =
        BroadcastOperationThreading.fromString(
            request.param("operation_threading"), BroadcastOperationThreading.SINGLE_THREAD);
    if (operationThreading == BroadcastOperationThreading.NO_THREADS) {
      // since we don't spawn, don't allow no_threads, but change it to a single thread
      operationThreading = BroadcastOperationThreading.SINGLE_THREAD;
    }
    broadcastPingRequest.operationThreading(operationThreading);
    client
        .admin()
        .cluster()
        .ping(
            broadcastPingRequest,
            new ActionListener<BroadcastPingResponse>() {
              @Override
              public void onResponse(BroadcastPingResponse response) {
                try {
                  XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
                  builder.startObject();
                  builder.field("ok", true);
                  buildBroadcastShardsHeader(builder, response);
                  builder.endObject();
                  channel.sendResponse(new XContentRestResponse(request, OK, builder));
                } catch (Exception e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new XContentThrowableRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
 @Override
 public void handleRequest(final RestRequest request, final RestChannel channel) {
   PutWarmerRequest putWarmerRequest = new PutWarmerRequest(request.param("name"));
   putWarmerRequest.listenerThreaded(false);
   SearchRequest searchRequest =
       new SearchRequest(Strings.splitStringByCommaToArray(request.param("index")))
           .types(Strings.splitStringByCommaToArray(request.param("type")))
           .source(request.content(), request.contentUnsafe());
   searchRequest.indicesOptions(
       IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));
   putWarmerRequest.searchRequest(searchRequest);
   putWarmerRequest.timeout(request.paramAsTime("timeout", putWarmerRequest.timeout()));
   putWarmerRequest.masterNodeTimeout(
       request.paramAsTime("master_timeout", putWarmerRequest.masterNodeTimeout()));
   client
       .admin()
       .indices()
       .putWarmer(
           putWarmerRequest, new AcknowledgedRestResponseActionListener(request, channel, logger));
 }
 @Override
 public void handleRequest(
     final RestRequest request, final RestChannel channel, final Client client) {
   ClusterStatsRequest clusterStatsRequest =
       new ClusterStatsRequest().nodesIds(request.paramAsStringArray("nodeId", null));
   clusterStatsRequest.timeout(request.param("timeout"));
   client
       .admin()
       .cluster()
       .clusterStats(clusterStatsRequest, new RestToXContentListener<>(channel));
 }
  @Override
  public void handleRequest(final RestRequest request, final RestChannel channel) {
    PutWarmerRequest putWarmerRequest = new PutWarmerRequest(request.param("name"));
    putWarmerRequest.listenerThreaded(false);
    SearchRequest searchRequest =
        new SearchRequest(RestActions.splitIndices(request.param("index")))
            .types(RestActions.splitTypes(request.param("type")))
            .source(request.content(), request.contentUnsafe());
    putWarmerRequest.searchRequest(searchRequest);
    client
        .admin()
        .indices()
        .putWarmer(
            putWarmerRequest,
            new ActionListener<PutWarmerResponse>() {
              @Override
              public void onResponse(PutWarmerResponse response) {
                try {
                  XContentBuilder builder = RestXContentBuilder.restContentBuilder(request);
                  builder
                      .startObject()
                      .field("ok", true)
                      .field("acknowledged", response.isAcknowledged());
                  builder.endObject();
                  channel.sendResponse(new XContentRestResponse(request, OK, builder));
                } catch (IOException e) {
                  onFailure(e);
                }
              }

              @Override
              public void onFailure(Throwable e) {
                try {
                  channel.sendResponse(new XContentThrowableRestResponse(request, e));
                } catch (IOException e1) {
                  logger.error("Failed to send failure response", e1);
                }
              }
            });
  }
  @Override
  public void handleRequest(
      final RestRequest request, final RestChannel channel, final Client client) {
    final GetRequest getRequest =
        new GetRequest(request.param("index"), request.param("type"), request.param("id"));
    getRequest.operationThreaded(true);
    getRequest.refresh(request.paramAsBoolean("refresh", getRequest.refresh()));
    getRequest.routing(
        request.param(
            "routing")); // order is important, set it after routing, so it will set the routing
    getRequest.parent(request.param("parent"));
    getRequest.preference(request.param("preference"));
    getRequest.realtime(request.paramAsBoolean("realtime", getRequest.realtime()));
    // don't get any fields back...
    getRequest.fields(Strings.EMPTY_ARRAY);
    // TODO we can also just return the document size as Content-Length

    client.get(
        getRequest,
        new RestResponseListener<GetResponse>(channel) {
          @Override
          public RestResponse buildResponse(GetResponse response) {
            if (!response.isExists()) {
              return new BytesRestResponse(NOT_FOUND);
            } else {
              return new BytesRestResponse(OK);
            }
          }
        });
  }