View Javadoc
1   /*
2    * Copyright 2021 TiKV Project Authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   */
17  
18  package org.tikv.common.streaming;
19  
20  import static java.util.Objects.requireNonNull;
21  
22  import java.util.ArrayList;
23  import java.util.Iterator;
24  import java.util.List;
25  import javax.annotation.Nonnull;
26  import org.tikv.kvproto.Coprocessor;
27  import org.tikv.kvproto.Errorpb;
28  
29  public class StreamingResponse implements Iterable {
30    private final Iterator<Coprocessor.Response> resultIterator;
31    private final List<Coprocessor.Response> responseList;
32  
33    @SuppressWarnings("unchecked")
34    public StreamingResponse(Iterator resultIterator) {
35      requireNonNull(resultIterator, "Streaming result cannot be null!");
36      this.resultIterator = resultIterator;
37      responseList = new ArrayList<>();
38      fetchStreamingResult();
39    }
40  
41    private void fetchStreamingResult() {
42      while (resultIterator.hasNext()) {
43        responseList.add(resultIterator.next());
44      }
45    }
46  
47    public boolean hasRegionError() {
48      for (Coprocessor.Response response : responseList) {
49        if (response.hasRegionError()) {
50          return true;
51        }
52      }
53  
54      return false;
55    }
56  
57    public Errorpb.Error getFirstRegionError() {
58      for (Coprocessor.Response response : responseList) {
59        if (response.hasRegionError()) {
60          return response.getRegionError();
61        }
62      }
63  
64      return null;
65    }
66  
67    public String getFirstOtherError() {
68      for (Coprocessor.Response response : responseList) {
69        if (!response.getOtherError().isEmpty()) {
70          return response.getOtherError();
71        }
72      }
73      return null;
74    }
75  
76    @Override
77    @Nonnull
78    public Iterator<Coprocessor.Response> iterator() {
79      return responseList.iterator();
80    }
81  }