@Test
 public void testDeleteByQueryWithNoIndices() {
   DeleteByQueryRequestBuilder delete = newDeleteByQuery().setQuery(QueryBuilders.matchAllQuery());
   delete.setIndicesOptions(IndicesOptions.fromOptions(false, true, true, false));
   assertDBQResponse(delete.get(), 0L, 0l, 0l, 0l);
   assertSearchContextsClosed();
 }
 /**
  * Build a random search request.
  *
  * @param randomSearchSourceBuilder builds a random {@link SearchSourceBuilder}. You can use
  *     {@link #randomSearchSourceBuilder(Supplier, Supplier, Supplier, Supplier)}.
  */
 public static SearchRequest randomSearchRequest(
     Supplier<SearchSourceBuilder> randomSearchSourceBuilder) throws IOException {
   SearchRequest searchRequest = new SearchRequest();
   if (randomBoolean()) {
     searchRequest.indices(generateRandomStringArray(10, 10, false, false));
   }
   if (randomBoolean()) {
     searchRequest.indicesOptions(
         IndicesOptions.fromOptions(
             randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean()));
   }
   if (randomBoolean()) {
     searchRequest.types(generateRandomStringArray(10, 10, false, false));
   }
   if (randomBoolean()) {
     searchRequest.preference(randomAsciiOfLengthBetween(3, 10));
   }
   if (randomBoolean()) {
     searchRequest.requestCache(randomBoolean());
   }
   if (randomBoolean()) {
     searchRequest.routing(randomAsciiOfLengthBetween(3, 10));
   }
   if (randomBoolean()) {
     searchRequest.scroll(randomPositiveTimeValue());
   }
   if (randomBoolean()) {
     searchRequest.searchType(randomFrom(SearchType.values()));
   }
   if (randomBoolean()) {
     searchRequest.source(randomSearchSourceBuilder.get());
   }
   return searchRequest;
 }
  @Test
  public void testSerialization() throws Exception {
    int iterations = randomIntBetween(5, 20);
    for (int i = 0; i < iterations; i++) {

      IndicesOptions indicesOptions =
          IndicesOptions.fromOptions(
              randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean());
      ClusterStateRequest clusterStateRequest =
          new ClusterStateRequest()
              .routingTable(randomBoolean())
              .metaData(randomBoolean())
              .nodes(randomBoolean())
              .blocks(randomBoolean())
              .indices("testindex", "testindex2")
              .indicesOptions(indicesOptions);

      Version testVersion =
          VersionUtils.randomVersionBetween(
              random(), Version.CURRENT.minimumCompatibilityVersion(), Version.CURRENT);
      BytesStreamOutput output = new BytesStreamOutput();
      output.setVersion(testVersion);
      clusterStateRequest.writeTo(output);

      StreamInput streamInput = StreamInput.wrap(output.bytes());
      streamInput.setVersion(testVersion);
      ClusterStateRequest deserializedCSRequest = new ClusterStateRequest();
      deserializedCSRequest.readFrom(streamInput);

      assertThat(deserializedCSRequest.routingTable(), equalTo(clusterStateRequest.routingTable()));
      assertThat(deserializedCSRequest.metaData(), equalTo(clusterStateRequest.metaData()));
      assertThat(deserializedCSRequest.nodes(), equalTo(clusterStateRequest.nodes()));
      assertThat(deserializedCSRequest.blocks(), equalTo(clusterStateRequest.blocks()));
      assertThat(deserializedCSRequest.indices(), equalTo(clusterStateRequest.indices()));

      if (testVersion.onOrAfter(Version.V_1_5_0)) {
        assertOptionsMatch(
            deserializedCSRequest.indicesOptions(), clusterStateRequest.indicesOptions());
      } else {
        // versions before V_1_5_0 use IndicesOptions.lenientExpandOpen()
        assertOptionsMatch(
            deserializedCSRequest.indicesOptions(), IndicesOptions.lenientExpandOpen());
      }
    }
  }
public class IndicesReplicationOperationRequest<T extends IndicesReplicationOperationRequest>
    extends ActionRequest<T> implements IndicesRequest {

  protected TimeValue timeout = ShardReplicationOperationRequest.DEFAULT_TIMEOUT;
  protected String[] indices;
  private IndicesOptions indicesOptions = IndicesOptions.fromOptions(false, false, true, false);

  protected ReplicationType replicationType = ReplicationType.DEFAULT;
  protected WriteConsistencyLevel consistencyLevel = WriteConsistencyLevel.DEFAULT;

  public TimeValue timeout() {
    return timeout;
  }

  /**
   * A timeout to wait if the delete by query operation can't be performed immediately. Defaults to
   * <tt>1m</tt>.
   */
  @SuppressWarnings("unchecked")
  public final T timeout(TimeValue timeout) {
    this.timeout = timeout;
    return (T) this;
  }

  /**
   * A timeout to wait if the delete by query operation can't be performed immediately. Defaults to
   * <tt>1m</tt>.
   */
  @SuppressWarnings("unchecked")
  public T timeout(String timeout) {
    this.timeout = TimeValue.parseTimeValue(timeout, null);
    return (T) this;
  }

  @Override
  public String[] indices() {
    return this.indices;
  }

  @Override
  public IndicesOptions indicesOptions() {
    return indicesOptions;
  }

  public T indicesOptions(IndicesOptions indicesOptions) {
    if (indicesOptions == null) {
      throw new IllegalArgumentException("IndicesOptions must not be null");
    }
    this.indicesOptions = indicesOptions;
    return (T) this;
  }

  /** The indices the request will execute against. */
  @SuppressWarnings("unchecked")
  public final T indices(String[] indices) {
    this.indices = indices;
    return (T) this;
  }

  public ReplicationType replicationType() {
    return this.replicationType;
  }

  /** Sets the replication type. */
  @SuppressWarnings("unchecked")
  public final T replicationType(ReplicationType replicationType) {
    if (replicationType == null) {
      throw new IllegalArgumentException("ReplicationType must not be null");
    }
    this.replicationType = replicationType;
    return (T) this;
  }

  /** Sets the replication type. */
  public final T replicationType(String replicationType) {
    return replicationType(ReplicationType.fromString(replicationType));
  }

  public WriteConsistencyLevel consistencyLevel() {
    return this.consistencyLevel;
  }

  /**
   * Sets the consistency level of write. Defaults to {@link
   * org.elasticsearch.action.WriteConsistencyLevel#DEFAULT}
   */
  @SuppressWarnings("unchecked")
  public final T consistencyLevel(WriteConsistencyLevel consistencyLevel) {
    if (consistencyLevel == null) {
      throw new IllegalArgumentException("WriteConsistencyLevel must not be null");
    }
    this.consistencyLevel = consistencyLevel;
    return (T) this;
  }

  @Override
  public ActionRequestValidationException validate() {
    return null;
  }

  @Override
  public void readFrom(StreamInput in) throws IOException {
    super.readFrom(in);
    replicationType = ReplicationType.fromId(in.readByte());
    consistencyLevel = WriteConsistencyLevel.fromId(in.readByte());
    timeout = TimeValue.readTimeValue(in);
    indices = in.readStringArray();
    indicesOptions = IndicesOptions.readIndicesOptions(in);
  }

  @Override
  public void writeTo(StreamOutput out) throws IOException {
    super.writeTo(out);
    out.writeByte(replicationType.id());
    out.writeByte(consistencyLevel.id());
    timeout.writeTo(out);
    out.writeStringArrayNullable(indices);
    indicesOptions.writeIndicesOptions(out);
  }
}
 /**
  * Constructs a new validate request against the provided indices. No indices provided means it
  * will run against all indices.
  */
 public ValidateQueryRequest(String... indices) {
   super(indices);
   indicesOptions(IndicesOptions.fromOptions(false, false, true, false));
 }
  public MultiSearchRequest add(
      BytesReference data,
      boolean contentUnsafe,
      @Nullable String[] indices,
      @Nullable String[] types,
      @Nullable String searchType,
      @Nullable String routing,
      IndicesOptions indicesOptions,
      boolean allowExplicitIndex)
      throws Exception {
    XContent xContent = XContentFactory.xContent(data);
    int from = 0;
    int length = data.length();
    byte marker = xContent.streamSeparator();
    while (true) {
      int nextMarker = findNextMarker(marker, from, data, length);
      if (nextMarker == -1) {
        break;
      }
      // support first line with \n
      if (nextMarker == 0) {
        from = nextMarker + 1;
        continue;
      }

      SearchRequest searchRequest = new SearchRequest();
      if (indices != null) {
        searchRequest.indices(indices);
      }
      if (indicesOptions != null) {
        searchRequest.indicesOptions(indicesOptions);
      }
      if (types != null && types.length > 0) {
        searchRequest.types(types);
      }
      if (routing != null) {
        searchRequest.routing(routing);
      }
      searchRequest.searchType(searchType);

      IndicesOptions defaultOptions = IndicesOptions.strictExpandOpenAndForbidClosed();
      boolean ignoreUnavailable = defaultOptions.ignoreUnavailable();
      boolean allowNoIndices = defaultOptions.allowNoIndices();
      boolean expandWildcardsOpen = defaultOptions.expandWildcardsOpen();
      boolean expandWildcardsClosed = defaultOptions.expandWildcardsClosed();

      // now parse the action
      if (nextMarker - from > 0) {
        try (XContentParser parser = xContent.createParser(data.slice(from, nextMarker - from))) {
          // Move to START_OBJECT, if token is null, its an empty data
          XContentParser.Token token = parser.nextToken();
          if (token != null) {
            assert token == XContentParser.Token.START_OBJECT;
            String currentFieldName = null;
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
              if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
              } else if (token.isValue()) {
                if ("index".equals(currentFieldName) || "indices".equals(currentFieldName)) {
                  if (!allowExplicitIndex) {
                    throw new ElasticsearchIllegalArgumentException(
                        "explicit index in multi search is not allowed");
                  }
                  searchRequest.indices(Strings.splitStringByCommaToArray(parser.text()));
                } else if ("type".equals(currentFieldName) || "types".equals(currentFieldName)) {
                  searchRequest.types(Strings.splitStringByCommaToArray(parser.text()));
                } else if ("search_type".equals(currentFieldName)
                    || "searchType".equals(currentFieldName)) {
                  searchRequest.searchType(parser.text());
                } else if ("query_cache".equals(currentFieldName)
                    || "queryCache".equals(currentFieldName)) {
                  searchRequest.queryCache(parser.booleanValue());
                } else if ("preference".equals(currentFieldName)) {
                  searchRequest.preference(parser.text());
                } else if ("routing".equals(currentFieldName)) {
                  searchRequest.routing(parser.text());
                } else if ("ignore_unavailable".equals(currentFieldName)
                    || "ignoreUnavailable".equals(currentFieldName)) {
                  ignoreUnavailable = parser.booleanValue();
                } else if ("allow_no_indices".equals(currentFieldName)
                    || "allowNoIndices".equals(currentFieldName)) {
                  allowNoIndices = parser.booleanValue();
                } else if ("expand_wildcards".equals(currentFieldName)
                    || "expandWildcards".equals(currentFieldName)) {
                  String[] wildcards = Strings.splitStringByCommaToArray(parser.text());
                  for (String wildcard : wildcards) {
                    if ("open".equals(wildcard)) {
                      expandWildcardsOpen = true;
                    } else if ("closed".equals(wildcard)) {
                      expandWildcardsClosed = true;
                    } else {
                      throw new ElasticsearchIllegalArgumentException(
                          "No valid expand wildcard value [" + wildcard + "]");
                    }
                  }
                }
              } else if (token == XContentParser.Token.START_ARRAY) {
                if ("index".equals(currentFieldName) || "indices".equals(currentFieldName)) {
                  if (!allowExplicitIndex) {
                    throw new ElasticsearchIllegalArgumentException(
                        "explicit index in multi search is not allowed");
                  }
                  searchRequest.indices(parseArray(parser));
                } else if ("type".equals(currentFieldName) || "types".equals(currentFieldName)) {
                  searchRequest.types(parseArray(parser));
                } else if ("expand_wildcards".equals(currentFieldName)
                    || "expandWildcards".equals(currentFieldName)) {
                  String[] wildcards = parseArray(parser);
                  for (String wildcard : wildcards) {
                    if ("open".equals(wildcard)) {
                      expandWildcardsOpen = true;
                    } else if ("closed".equals(wildcard)) {
                      expandWildcardsClosed = true;
                    } else {
                      throw new ElasticsearchIllegalArgumentException(
                          "No valid expand wildcard value [" + wildcard + "]");
                    }
                  }
                } else {
                  throw new ElasticsearchParseException(
                      currentFieldName + " doesn't support arrays");
                }
              }
            }
          }
        }
      }
      searchRequest.indicesOptions(
          IndicesOptions.fromOptions(
              ignoreUnavailable,
              allowNoIndices,
              expandWildcardsOpen,
              expandWildcardsClosed,
              defaultOptions));

      // move pointers
      from = nextMarker + 1;
      // now for the body
      nextMarker = findNextMarker(marker, from, data, length);
      if (nextMarker == -1) {
        break;
      }

      searchRequest.source(data.slice(from, nextMarker - from), contentUnsafe);
      // move pointers
      from = nextMarker + 1;

      add(searchRequest);
    }

    return this;
  }
  /**
   * Parses restore definition
   *
   * @param source restore definition
   * @return this request
   */
  public RestoreSnapshotRequest source(Map source) {
    boolean ignoreUnavailable = IndicesOptions.lenient().ignoreUnavailable();
    boolean allowNoIndices = IndicesOptions.lenient().allowNoIndices();
    boolean expandWildcardsOpen = IndicesOptions.lenient().expandWildcardsOpen();
    boolean expandWildcardsClosed = IndicesOptions.lenient().expandWildcardsClosed();

    for (Map.Entry<String, Object> entry : ((Map<String, Object>) source).entrySet()) {
      String name = entry.getKey();
      if (name.equals("indices")) {
        if (entry.getValue() instanceof String) {
          indices(Strings.splitStringByCommaToArray((String) entry.getValue()));
        } else if (entry.getValue() instanceof ArrayList) {
          indices((ArrayList<String>) entry.getValue());
        } else {
          throw new ElasticSearchIllegalArgumentException(
              "malformed indices section, should be an array of strings");
        }
      } else if (name.equals("ignore_unavailable") || name.equals("ignoreUnavailable")) {
        assert entry.getValue() instanceof String;
        ignoreUnavailable = Boolean.valueOf(entry.getValue().toString());
      } else if (name.equals("allow_no_indices") || name.equals("allowNoIndices")) {
        assert entry.getValue() instanceof String;
        allowNoIndices = Boolean.valueOf(entry.getValue().toString());
      } else if (name.equals("expand_wildcards_open") || name.equals("expandWildcardsOpen")) {
        assert entry.getValue() instanceof String;
        expandWildcardsOpen = Boolean.valueOf(entry.getValue().toString());
      } else if (name.equals("expand_wildcards_closed") || name.equals("expandWildcardsClosed")) {
        assert entry.getValue() instanceof String;
        expandWildcardsClosed = Boolean.valueOf(entry.getValue().toString());
      } else if (name.equals("settings")) {
        if (!(entry.getValue() instanceof Map)) {
          throw new ElasticSearchIllegalArgumentException(
              "malformed settings section, should indices an inner object");
        }
        settings((Map<String, Object>) entry.getValue());
      } else if (name.equals("include_global_state")) {
        if (!(entry.getValue() instanceof Boolean)) {
          throw new ElasticSearchIllegalArgumentException(
              "malformed include_global_state, should be boolean");
        }
        includeGlobalState((Boolean) entry.getValue());
      } else if (name.equals("rename_pattern")) {
        if (entry.getValue() instanceof String) {
          renamePattern((String) entry.getValue());
        } else {
          throw new ElasticSearchIllegalArgumentException("malformed rename_pattern");
        }
      } else if (name.equals("rename_replacement")) {
        if (entry.getValue() instanceof String) {
          renameReplacement((String) entry.getValue());
        } else {
          throw new ElasticSearchIllegalArgumentException("malformed rename_replacement");
        }
      } else {
        throw new ElasticSearchIllegalArgumentException("Unknown parameter " + name);
      }
    }
    indicesOptions(
        IndicesOptions.fromOptions(
            ignoreUnavailable, allowNoIndices, expandWildcardsOpen, expandWildcardsClosed));
    return this;
  }